Convert UTC datetime string to local datetime

后端 未结 13 946
醉话见心
醉话见心 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
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-22 05:48

    Consolidating the answer from franksands into a convenient method.

    import calendar
    import datetime
    
    def to_local_datetime(utc_dt):
        """
        convert from utc datetime to a locally aware datetime according to the host timezone
    
        :param utc_dt: utc datetime
        :return: local timezone datetime
        """
        return datetime.datetime.fromtimestamp(calendar.timegm(utc_dt.timetuple()))
    
    0 讨论(0)
  • 2020-11-22 05:50
    import datetime
    
    def utc_str_to_local_str(utc_str: str, utc_format: str, local_format: str):
        """
        :param utc_str: UTC time string
        :param utc_format: format of UTC time string
        :param local_format: format of local time string
        :return: local time string
        """
        temp1 = datetime.datetime.strptime(utc_str, utc_format)
        temp2 = temp1.replace(tzinfo=datetime.timezone.utc)
        local_time = temp2.astimezone()
        return local_time.strftime(local_format)
    
    utc = '2018-10-17T00:00:00.111Z'
    utc_fmt = '%Y-%m-%dT%H:%M:%S.%fZ'
    local_fmt = '%Y-%m-%dT%H:%M:%S+08:00'
    local_string = utc_str_to_local_str(utc, utc_fmt, local_fmt)
    print(local_string)   # 2018-10-17T08:00:00+08:00
    

    for example, my timezone is '+08:00'. input utc = 2018-10-17T00:00:00.111Z, then I will get output = 2018-10-17T08:00:00+08:00

    0 讨论(0)
  • 2020-11-22 06:01

    See the datetime documentation on tzinfo objects. You have to implement the timezones you want to support yourself. The are examples at the bottom of the documentation.

    Here's a simple example:

    from datetime import datetime,tzinfo,timedelta
    
    class Zone(tzinfo):
        def __init__(self,offset,isdst,name):
            self.offset = offset
            self.isdst = isdst
            self.name = name
        def utcoffset(self, dt):
            return timedelta(hours=self.offset) + self.dst(dt)
        def dst(self, dt):
                return timedelta(hours=1) if self.isdst else timedelta(0)
        def tzname(self,dt):
             return self.name
    
    GMT = Zone(0,False,'GMT')
    EST = Zone(-5,False,'EST')
    
    print datetime.utcnow().strftime('%m/%d/%Y %H:%M:%S %Z')
    print datetime.now(GMT).strftime('%m/%d/%Y %H:%M:%S %Z')
    print datetime.now(EST).strftime('%m/%d/%Y %H:%M:%S %Z')
    
    t = datetime.strptime('2011-01-21 02:37:21','%Y-%m-%d %H:%M:%S')
    t = t.replace(tzinfo=GMT)
    print t
    print t.astimezone(EST)
    

    Output

    01/22/2011 21:52:09 
    01/22/2011 21:52:09 GMT
    01/22/2011 16:52:09 EST
    2011-01-21 02:37:21+00:00
    2011-01-20 21:37:21-05:00a
    
    0 讨论(0)
  • 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.

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