How do you convert a naive datetime to DST-aware datetime in Python?

前端 未结 2 1202
情歌与酒
情歌与酒 2021-01-01 19:05

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,

相关标签:
2条回答
  • 2021-01-01 19:53

    with Python 3.9's zoneinfo:

    from datetime import datetime
    from zoneinfo import ZoneInfo   
    
    naive_datetime = datetime(2011, 10, 26, 12, 0, 0)
    
    user_tz_preference = ZoneInfo('US/Pacific')
    user_datetime = naive_datetime.replace(tzinfo=user_tz_preference) # safe with zoneinfo
    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:00
    print(utc_datetime.isoformat())
    # 2011-10-26T19:00:00+00:00
    

    docs

    0 讨论(0)
  • 2021-01-01 19:56

    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
    
    0 讨论(0)
提交回复
热议问题