How Do You Convert A Naive Datetime To Dst-aware Datetime In Python?
I'm currently working on the backend for a calendaring system that returns naive Python datetimes. The way the front end works is the user creates various calendar events, and the
Solution 1:
Pytz's localize
function can do this: http://pytz.sourceforge.net/#localized-times-and-date-arithmetic
from datetime import datetime
import pytz
tz = pytz.timezone('US/Pacific')
naive_dt = datetime(2020, 10, 5, 15, 0, 0)
utc_dt = tz.localize(naive_dt, is_dst=None).astimezone(pytz.utc)
# -> 2020-10-05 22:00:00+00:00
Solution 2:
With zoneinfo
from Python 3.9's standard lib:
from datetime import datetime
from zoneinfo import ZoneInfo
naive_datetime = datetime(2011, 10, 26, 12, 0, 0)
user_tz_preference = ZoneInfo('US/Pacific')
# it is safe to replace the tzinfo:
user_datetime = naive_datetime.replace(tzinfo=user_tz_preference)
# ...or set it directly:
user_datetime = datetime(2011, 10, 26, 12, tzinfo=ZoneInfo('US/Pacific'))
# astimezone works as before:
utc_datetime = user_datetime.astimezone(ZoneInfo('UTC'))
print(repr(user_datetime))
# datetime.datetime(2011, 10, 26, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='US/Pacific'))print(user_datetime.isoformat())
# 2011-10-26T12:00:00-07:00print(utc_datetime.isoformat())
# 2011-10-26T19:00:00+00:00
Post a Comment for "How Do You Convert A Naive Datetime To Dst-aware Datetime In Python?"