How to convert local time string to UTC?

后端 未结 23 1209
离开以前
离开以前 2020-11-22 04:18

How do I convert a datetime string in local time to a string in UTC time?

I\'m sure I\'ve done this before, but can\'t find it and SO will hopefull

相关标签:
23条回答
  • 2020-11-22 05:02

    In python3:

    pip install python-dateutil

    from dateutil.parser import tz
    
    mydt.astimezone(tz.gettz('UTC')).replace(tzinfo=None) 
    
    0 讨论(0)
  • 2020-11-22 05:03
    import time
    
    import datetime
    
    def Local2UTC(LocalTime):
    
        EpochSecond = time.mktime(LocalTime.timetuple())
        utcTime = datetime.datetime.utcfromtimestamp(EpochSecond)
    
        return utcTime
    
    >>> LocalTime = datetime.datetime.now()
    
    >>> UTCTime = Local2UTC(LocalTime)
    
    >>> LocalTime.ctime()
    
    'Thu Feb  3 22:33:46 2011'
    
    >>> UTCTime.ctime()
    
    'Fri Feb  4 05:33:46 2011'
    
    0 讨论(0)
  • 2020-11-22 05:04
    def local_to_utc(t):
        secs = time.mktime(t)
        return time.gmtime(secs)
    
    def utc_to_local(t):
        secs = calendar.timegm(t)
        return time.localtime(secs)
    

    Source: http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html

    Example usage from bd808: If your source is a datetime.datetime object t, call as:

    local_to_utc(t.timetuple())
    
    0 讨论(0)
  • 2020-11-22 05:05

    This thread seems to be missing an option available since Python 3.6: datetime.astimezone(tz=None) can be used to get an aware datetime object representing local time (docs). This can then easily be converted to UTC.

    from datetime import datetime, timezone
    s = "2008-09-17 14:02:00"
    
    # to datetime object:
    dt = datetime.fromisoformat(s) # Python 3.7
    
    # I'm on time zone Europe/Berlin; CEST/UTC+2 during summer 2008
    dt = dt.astimezone()
    print(dt)
    # 2008-09-17 14:02:00+02:00
    
    # ...and to UTC:
    dtutc = dt.astimezone(timezone.utc)
    print(dtutc)
    # 2008-09-17 12:02:00+00:00
    

    There is one caveat though, see astimezone(None) gives aware datetime, unaware of DST.

    0 讨论(0)
  • 2020-11-22 05:07

    How about -

    time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))
    

    if seconds is None then it converts the local time to UTC time else converts the passed in time to UTC.

    0 讨论(0)
  • 2020-11-22 05:08

    You can do it with:

    >>> from time import strftime, gmtime, localtime
    >>> strftime('%H:%M:%S', gmtime()) #UTC time
    >>> strftime('%H:%M:%S', localtime()) # localtime
    
    0 讨论(0)
提交回复
热议问题