Guillaume
Guillaume

Reputation: 1921

Add datetime offset to UTC timestamp

I have in my code some datetime timestamps in UTC like "2022-05-20 01:00:00+00:00" and I wish to apply to them an offset like "+10:00" (or "+1000") and get as a result "2022-05-20 11:00:00+00:00"

I don't know the name of the timezone that I want to convert to, just what's its offset compared to UTC.

Is there a more direct way than applying a timedelta to my timestamp ?

Upvotes: 0

Views: 2323

Answers (2)

deceze
deceze

Reputation: 522636

Note that 2022-05-20 01:00:00+00:00 and 2022-05-20 11:00:00+00:00 are not the same timestamp, they're two arbitrary times with no obvious relation. What you likely want is 2022-05-20 11:00:00+10:00, which is the same timestamp as the first one, just in a different timezone. To get there is fairly simple:

>>> from datetime import *
>>> ts = '2022-05-20 01:00:00+00:00'
>>> dt = datetime.strptime(ts, '%Y-%m-%d %H:%M:%S%z')
datetime.datetime(2022, 5, 20, 1, 0, tzinfo=datetime.timezone.utc)
>>> tz = timezone(timedelta(hours=10))
datetime.timezone(datetime.timedelta(seconds=36000))
>>> dt_loc = dt.astimezone(tz)
datetime.datetime(2022, 5, 20, 11, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=36000)))
>>> print(dt_loc)
2022-05-20 11:00:00+10:00

If you have the offset just as a string, it's simple enough to turn it into a timezone:

>>> datetime.strptime('+10:00', '%z').tzinfo
datetime.timezone(datetime.timedelta(seconds=36000))

Works for positive and negative offsets.

Upvotes: 3

Adid
Adid

Reputation: 1584

You can use the timedelta object to add time to an existing datetime:

from datetime import timedelta, datetime
from pytz import UTC

original_time = datetime(2022, 5, 20, 1, 0, 0, tzinfo=UTC)  # 2022-05-20 01:00:00+00:00
time_diff = timedelta(hours=10)
new_time = original_time + time_diff  # 2022-05-20 11:00:00+00:00

Upvotes: 0

Related Questions