How to convert local time string to UTC?

后端 未结 23 1206
离开以前
离开以前 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 04:48

    I have this code in one of my projects:

    from datetime import datetime
    ## datetime.timezone works in newer versions of python
    try:
        from datetime import timezone
        utc_tz = timezone.utc
    except:
        import pytz
        utc_tz = pytz.utc
    
    def _to_utc_date_string(ts):
        # type (Union[date,datetime]]) -> str
        """coerce datetimes to UTC (assume localtime if nothing is given)"""
        if (isinstance(ts, datetime)):
            try:
                ## in python 3.6 and higher, ts.astimezone() will assume a
                ## naive timestamp is localtime (and so do we)
                ts = ts.astimezone(utc_tz)
            except:
                ## in python 2.7 and 3.5, ts.astimezone() will fail on
                ## naive timestamps, but we'd like to assume they are
                ## localtime
                import tzlocal
                ts = tzlocal.get_localzone().localize(ts).astimezone(utc_tz)
        return ts.strftime("%Y%m%dT%H%M%SZ")
    
    0 讨论(0)
  • 2020-11-22 04:48

    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 04:49

    Here's a summary of common Python time conversions.

    Some methods drop fractions of seconds, and are marked with (s). An explicit formula such as ts = (d - epoch) / unit can be used instead (thanks jfs).

    • struct_time (UTC) → POSIX (s):
      calendar.timegm(struct_time)
    • Naïve datetime (local) → POSIX (s):
      calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())
      (exception during DST transitions, see comment from jfs)
    • Naïve datetime (UTC) → POSIX (s):
      calendar.timegm(dt.utctimetuple())
    • Aware datetime → POSIX (s):
      calendar.timegm(dt.utctimetuple())
    • POSIX → struct_time (UTC, s):
      time.gmtime(t)
      (see comment from jfs)
    • Naïve datetime (local) → struct_time (UTC, s):
      stz.localize(dt, is_dst=None).utctimetuple()
      (exception during DST transitions, see comment from jfs)
    • Naïve datetime (UTC) → struct_time (UTC, s):
      dt.utctimetuple()
    • Aware datetime → struct_time (UTC, s):
      dt.utctimetuple()
    • POSIX → Naïve datetime (local):
      datetime.fromtimestamp(t, None)
      (may fail in certain conditions, see comment from jfs below)
    • struct_time (UTC) → Naïve datetime (local, s):
      datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
      (can't represent leap seconds, see comment from jfs)
    • Naïve datetime (UTC) → Naïve datetime (local):
      dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
    • Aware datetime → Naïve datetime (local):
      dt.astimezone(tz).replace(tzinfo=None)
    • POSIX → Naïve datetime (UTC):
      datetime.utcfromtimestamp(t)
    • struct_time (UTC) → Naïve datetime (UTC, s):
      datetime.datetime(*struct_time[:6])
      (can't represent leap seconds, see comment from jfs)
    • Naïve datetime (local) → Naïve datetime (UTC):
      stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)
      (exception during DST transitions, see comment from jfs)
    • Aware datetime → Naïve datetime (UTC):
      dt.astimezone(UTC).replace(tzinfo=None)
    • POSIX → Aware datetime:
      datetime.fromtimestamp(t, tz)
      (may fail for non-pytz timezones)
    • struct_time (UTC) → Aware datetime (s):
      datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz)
      (can't represent leap seconds, see comment from jfs)
    • Naïve datetime (local) → Aware datetime:
      stz.localize(dt, is_dst=None)
      (exception during DST transitions, see comment from jfs)
    • Naïve datetime (UTC) → Aware datetime:
      dt.replace(tzinfo=UTC)

    Source: taaviburns.ca

    0 讨论(0)
  • 2020-11-22 04:50

    If you already have a datetime object my_dt you can change it to UTC with:

    datetime.datetime.utcfromtimestamp(my_dt.timestamp())
    
    0 讨论(0)
  • 2020-11-22 04:52

    Thanks @rofly, the full conversion from string to string is as follows:

    time.strftime("%Y-%m-%d %H:%M:%S", 
                  time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00", 
                                                        "%Y-%m-%d %H:%M:%S"))))
    

    My summary of the time/calendar functions:

    time.strptime
    string --> tuple (no timezone applied, so matches string)

    time.mktime
    local time tuple --> seconds since epoch (always local time)

    time.gmtime
    seconds since epoch --> tuple in UTC

    and

    calendar.timegm
    tuple in UTC --> seconds since epoch

    time.localtime
    seconds since epoch --> tuple in local timezone

    0 讨论(0)
  • 2020-11-22 04:52

    Simple

    I did it like this:

    >>> utc_delta = datetime.utcnow()-datetime.now()
    >>> utc_time = datetime(2008, 9, 17, 14, 2, 0) + utc_delta
    >>> print(utc_time)
    2008-09-17 19:01:59.999996
    

    Fancy Implementation

    If you want to get fancy, you can turn this into a functor:

    class to_utc():
        utc_delta = datetime.utcnow() - datetime.now()
    
        def __call__(cls, t):
            return t + cls.utc_delta
    

    Result:

    >>> utc_converter = to_utc()
    >>> print(utc_converter(datetime(2008, 9, 17, 14, 2, 0)))
    2008-09-17 19:01:59.999996
    
    0 讨论(0)
提交回复
热议问题