Convert UTC datetime string to local datetime

后端 未结 13 973
醉话见心
醉话见心 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:01

    This answer should be helpful if you don't want to use any other modules besides datetime.

    datetime.utcfromtimestamp(timestamp) returns a naive datetime object (not an aware one). Aware ones are timezone aware, and naive are not. You want an aware one if you want to convert between timezones (e.g. between UTC and local time).

    If you aren't the one instantiating the date to start with, but you can still create a naive datetime object in UTC time, you might want to try this Python 3.x code to convert it:

    import datetime
    
    d=datetime.datetime.strptime("2011-01-21 02:37:21", "%Y-%m-%d %H:%M:%S") #Get your naive datetime object
    d=d.replace(tzinfo=datetime.timezone.utc) #Convert it to an aware datetime object in UTC time.
    d=d.astimezone() #Convert it to your local timezone (still aware)
    print(d.strftime("%d %b %Y (%I:%M:%S:%f %p) %Z")) #Print it with a directive of choice
    

    Be careful not to mistakenly assume that if your timezone is currently MDT that daylight savings doesn't work with the above code since it prints MST. You'll note that if you change the month to August, it'll print MDT.

    Another easy way to get an aware datetime object (also in Python 3.x) is to create it with a timezone specified to start with. Here's an example, using UTC:

    import datetime, sys
    
    aware_utc_dt_obj=datetime.datetime.now(datetime.timezone.utc) #create an aware datetime object
    dt_obj_local=aware_utc_dt_obj.astimezone() #convert it to local time
    
    #The following section is just code for a directive I made that I liked.
    if sys.platform=="win32":
        directive="%#d %b %Y (%#I:%M:%S:%f %p) %Z"
    else:
        directive="%-d %b %Y (%-I:%M:%S:%f %p) %Z"
    
    print(dt_obj_local.strftime(directive))
    

    If you use Python 2.x, you'll probably have to subclass datetime.tzinfo and use that to help you create an aware datetime object, since datetime.timezone doesn't exist in Python 2.x.

提交回复
热议问题