Python: How to convert a timezone aware timestamp to UTC without knowing if DST is in effect

后端 未结 1 1157
不思量自难忘°
不思量自难忘° 2021-01-01 13:33

I am trying to convert a naive timestamp that is always in Pacific time to UTC time. In the code below, I\'m able to specify that this timestamp I have is in Pacific time, b

1条回答
  •  醉梦人生
    2021-01-01 14:15

    Use the localize method:

    import pytz
    import datetime
    naive_date = datetime.datetime.strptime("2013-10-21 08:44:08", "%Y-%m-%d %H:%M:%S")
    localtz = pytz.timezone('America/Los_Angeles')
    date_aware_la = localtz.localize(naive_date)
    print(date_aware_la)   # 2013-10-21 08:44:08-07:00
    

    This is covered in the "Example & Usage" section of the pytz documentation.

    And then continuing to UTC:

    utc_date = date_aware_la.astimezone(pytz.utc)
    print(utc_date)
    

    0 讨论(0)
提交回复
热议问题