Python Datetime with Timezones: Examples and Reference

Python Datetime with Timezones: Examples and Reference

Last updated:
Table of Contents

All examples use Python 3.6+ unless otherwise stated

Current datetime in UTC

To get the current timestamp in UTC timezone, use datetime.now() passing timezone.utc:

from datetime import datetime, timezone

dt = datetime.now(timezone.utc)
dt
# datetime.datetime(2021, 1, 3, 21, 14, 51, 547415, tzinfo=datetime.timezone.utc)

Current datetime in Timezone

Use datetime.now(timezone(timedelta(hours=<offset_hours>)))

from datetime import datetime, timezone, timedelta

dt = datetime.now(timezone(timedelta(hours=-3)))
dt
# datetime.datetime(2021, 1, 3, 18, 29, 54, 46852, tzinfo=datetime.timezone(datetime.timedelta(-1, 75600)))

Datetime with Offset Timezone

Timezones can be defined by the offset with respect to UTC.

from datetime import datetime, timezone, timedelta

# UTC+03:00
tz = timezone(timedelta(hours=3))

# May 10, 2016 at 12:30:00, on UTC-03:00
dt = datetime(2016,5,10,12,30,0,0, tzinfo=tz)
dt
# datetime.datetime(2016, 5, 10, 12, 30, tzinfo=datetime.timezone(datetime.timedelta(0, 10800)))

Add UTC Timezone to naive datetime

In other words, attach Timezone information to datetime objects that were created without timezone information, without adjusting the time

from datetime import datetime, timezone

# this is a naive datetime without timezone information
naive_dt = datetime.now()
naive_dt
# datetime.datetime(2021, 1, 3, 18, 33, 50, 631654)

dt_with_tz = naive_dt.replace(tzinfo=timezone.utc)
dt_with_tz
# datetime.datetime(2021, 1, 3, 18, 33, 50, 631654, tzinfo=datetime.timezone.utc)

Convert datetime to another timezone

Use .astimezone(<other_time_zone>):

from datetime import datetime, timezone, timedelta

# 21:36 in UTC
base_dt = datetime.now(timezone.utc)
base_dt
# datetime.datetime(2021, 1, 3, 21, 36, 6, 339737, tzinfo=datetime.timezone.utc)

# becomes 23:36 in UTC+02:00
dt_in_utc_plus_2 = base_dt.astimezone(timezone(timedelta(hours=2)))
dt_in_utc_plus_2
# datetime.datetime(2021, 1, 3, 23, 36, 6, 339737, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))

Dialogue & Discussion