Convert UTC datetime string to local datetime

后端 未结 13 1111
醉话见心
醉话见心 2020-11-22 05:37

I\'ve never had to convert time to and from UTC. Recently had a request to have my app be timezone aware, and I\'ve been running myself in circles. Lots of information on co

13条回答
  •  轮回少年
    2020-11-22 05:48

    If you want to get the correct result even for the time that corresponds to an ambiguous local time (e.g., during a DST transition) and/or the local utc offset is different at different times in your local time zone then use pytz timezones:

    #!/usr/bin/env python
    from datetime import datetime
    import pytz    # $ pip install pytz
    import tzlocal # $ pip install tzlocal
    
    local_timezone = tzlocal.get_localzone() # get pytz tzinfo
    utc_time = datetime.strptime("2011-01-21 02:37:21", "%Y-%m-%d %H:%M:%S")
    local_time = utc_time.replace(tzinfo=pytz.utc).astimezone(local_timezone)
    

提交回复
热议问题