Handling timezones in python
from zoneinfo import ZoneInfo
from datetime import datetime , timezone
datetime .now (timezone .utc )
from datetime import datetime
from zoneinfo import ZoneInfo
datetime .now (ZoneInfo ("Europe/Stockholm" )).date ()
Convert datetime to date in a timezone
dt = datetime (2022 , 7 , 8 , tzinfo = timezone .utc )
dt .astimezone (ZoneInfo ("Europe/Stockholm" )).date ()
>> > date (2022 , 4 , 5 )
Display UTC time as local time
dt = datetime (2022 , 7 , 8 , tzinfo = timezone .utc )
tz = ZoneInfo ("Europe/Stockholm" )
dt .astimezone (tz ).strftime ("%x %X" )
>> > '04/05/22 22:00:00'
Convert ISO-8601 string to UTC datetime
dt_str = "2022-07-08T02:00:00+02:00"
datetime .fromisoformat (dt_str ).astimezone (timezone .utc )
>> > datetime .datetime (2022 , 7 , 8 , 0 , 0 , tzinfo = datetime .timezone .utc )
tz = ZoneInfo ("Europe/Stockholm" )
local_dt = datetime (2022 , 7 , 8 , 0 , 38 , tzinfo = tz )
local_dt .isoformat ()
>> > '2022-07-08T00:38:00+02:00'
new_dt = local_dt .astimezone (timezone .utc ) + timedelta (hours = 2 )
new_dt .astimezone (tz ).isoformat ()
>> > '2022-07-08T02:38:00+02:00'
tz = ZoneInfo ("Europe/Stockholm" )
local_dt = datetime (2022 , 7 , 8 , 0 , 38 , tzinfo = tz )
local_dt .date () + timedelta (days = 120 )
>> > datetime .date (2022 , 11 , 5 )