Convert UTC datetime string to local datetime

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

    Here is a quick and dirty version that uses the local systems settings to work out the time difference. NOTE: This will not work if you need to convert to a timezone that your current system is not running in. I have tested this with UK settings under BST timezone

    from datetime import datetime
    def ConvertP4DateTimeToLocal(timestampValue):
       assert isinstance(timestampValue, int)
    
       # get the UTC time from the timestamp integer value.
       d = datetime.utcfromtimestamp( timestampValue )
    
       # calculate time difference from utcnow and the local system time reported by OS
       offset = datetime.now() - datetime.utcnow()
    
       # Add offset to UTC time and return it
       return d + offset
    

提交回复
热议问题