如何将本地时间的datetime字符串转换为UTC时间的字符串?

我确信我以前做过这个,但找不到它,所以希望将来能帮助我(和其他人)做到这一点。

澄清:例如,如果我的本地时区(+10)是2008-09-17 14:02:00,我希望生成一个具有等效UTC时间的字符串:2008-09-17 04:02:00。

此外,从http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/请注意,一般来说,这是不可能的,因为DST和其他问题没有从本地时间到UTC时间的唯一转换。


当前回答

简单地说,要将任何datetime日期转换为UTC时间:

from datetime import datetime

def to_utc(date):
    return datetime(*date.utctimetuple()[:6])

让我们用一个例子来解释。首先,我们需要从字符串中创建一个datetime:

>>> date = datetime.strptime("11 Feb 2011 17:33:54 -0800", "%d %b %Y %H:%M:%S %z")

然后,我们可以调用函数:

>>> to_utc(date)
datetime.datetime(2011, 2, 12, 1, 33, 54)

函数如何一步步工作:

>>> date.utctimetuple()
time.struct_time(tm_year=2011, tm_mon=2, tm_mday=12, tm_hour=1, tm_min=33, tm_sec=54, tm_wday=5, tm_yday=43, tm_isdst=0)
>>> date.utctimetuple()[:6]
(2011, 2, 12, 1, 33, 54)
>>> datetime(*date.utctimetuple()[:6])
datetime.datetime(2011, 2, 12, 1, 33, 54)

其他回答

怎么样——

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

如果seconds为None,则将本地时间转换为UTC时间,否则将传入的时间转换为UTC时间。

如果你喜欢datetime.datetime:

dt = datetime.strptime("2008-09-17 14:04:00","%Y-%m-%d %H:%M:%S")
utc_struct_time = time.gmtime(time.mktime(dt.timetuple()))
utc_dt = datetime.fromtimestamp(time.mktime(utc_struct_time))
print dt.strftime("%Y-%m-%d %H:%M:%S")

Python 3.6以来可用的选项:datetime.astimezone(tz=None)可用于获取表示本地时间的可感知datetime对象(docs)。然后可以很容易地将其转换为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

注意:虽然描述的到UTC的转换工作得非常好,但.astimezone()将datetime对象的tzinfo设置为timedelta派生的时区-所以不要期望从它得到任何“dst感知”。注意这里的时间增量运算。当然,除非您先转换为UTC。 相关:获取Windows上的本地时区名称(Python 3.9 zoneinfo)

我在我的一个项目中有这样的代码:

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")

下面是一些常见的Python时间转换的总结。

有些方法以秒为单位,用(s)标记。可以使用显式公式,如ts = (d - epoch) / unit代替(感谢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)

来源:taaviburns.ca