Skip to content

Instantly share code, notes, and snippets.

@kaar
Last active January 10, 2023 09:21
Show Gist options
  • Save kaar/520c01a9b9a24da6355959abd8138e46 to your computer and use it in GitHub Desktop.
Save kaar/520c01a9b9a24da6355959abd8138e46 to your computer and use it in GitHub Desktop.

Handling timezones in python

TLDW

Use ZoneInfo

from zoneinfo import ZoneInfo

Current time

from datetime import datetime, timezone

datetime.now(timezone.utc)

Current date

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)

Duration math in 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'

Calendar math on dates

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment