Convert UTC datetime string to local datetime

后端 未结 13 1167
醉话见心
醉话见心 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 06:09

    If you don't want to provide your own tzinfo objects, check out the python-dateutil library. It provides tzinfo implementations on top of a zoneinfo (Olson) database such that you can refer to time zone rules by a somewhat canonical name.

    from datetime import datetime
    from dateutil import tz
    
    # METHOD 1: Hardcode zones:
    from_zone = tz.gettz('UTC')
    to_zone = tz.gettz('America/New_York')
    
    # METHOD 2: Auto-detect zones:
    from_zone = tz.tzutc()
    to_zone = tz.tzlocal()
    
    # utc = datetime.utcnow()
    utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')
    
    # Tell the datetime object that it's in UTC time zone since 
    # datetime objects are 'naive' by default
    utc = utc.replace(tzinfo=from_zone)
    
    # Convert time zone
    central = utc.astimezone(to_zone)
    

    Edit Expanded example to show strptime usage

    Edit 2 Fixed API usage to show better entry point method

    Edit 3 Included auto-detect methods for timezones (Yarin)

提交回复
热议问题