如何将本地时间的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时间的唯一转换。


当前回答

在python3:

PIP安装python-dateutil

from dateutil.parser import tz

mydt.astimezone(tz.gettz('UTC')).replace(tzinfo=None) 

其他回答

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

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

下面是Python3.9中本地zoneinfo模块的示例:

from datetime import datetime
from zoneinfo import ZoneInfo

# Get timezone we're trying to convert from
local_tz = ZoneInfo("America/New_York")
# UTC timezone
utc_tz = ZoneInfo("UTC")

dt = datetime.strptime("2021-09-20 17:20:00","%Y-%m-%d %H:%M:%S")
dt = dt.replace(tzinfo=local_tz)
dt_utc = dt.astimezone(utc_tz)

print(dt.strftime("%Y-%m-%d %H:%M:%S"))
print(dt_utc.strftime("%Y-%m-%d %H:%M:%S"))

在转换的时区不反映系统本地时区的情况下,这可能比仅使用dt.astimezone()更可取。不必依赖外部库也很好。

注意:这可能在Windows系统上不起作用,因为zoneinfo依赖于可能不存在的IANA数据库。tzdata包可以作为解决方案安装。它是第一方包,但不在标准库中。

下面是一些常见的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

给那些被点赞最多的答案搞糊涂的人。你可以在python中通过生成一个datetime对象将一个datetime字符串转换为utc时间,然后你可以使用astimezone(pytz.utc)来获得utc格式的datetime。

如。

假设我们有一个isoformat的本地日期时间字符串2021-09-02T19:02:00Z

现在将该字符串转换为utc datetime。首先需要使用字符串by生成datetime对象

dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ')

这将给你一个python datetime对象,然后你可以使用astimezone(pytz.utc)来获得utc datetime like

dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ') dt = dt.astimezone(pytz.utc)

这将为您提供utc格式的datetime对象,然后您可以使用dt将其转换为字符串。Y strftime(“% - % - % d % H: % m: % S”)

完整代码eg:

from datetime import datetime
import pytz

def converLocalToUTC(datetime, getString=True, format="%Y-%m-%d %H:%M:%S"):
    dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ')
    dt = dt.astimezone(pytz.utc)
    
    if getString:
        return dt.strftime(format)
    return dt

然后你可以称它为

converLocalToUTC(“2021 - 09 - 02 t19:02:00z”)

求助于 https://stackoverflow.com/a/79877/7756843

谢谢@rofly,从字符串到字符串的完整转换如下:

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

我对时间/日历功能的总结:

time.strptime 字符串——>元组(没有应用时区,所以匹配字符串)

time.mktime 本地时间元组——自epoch以来>秒(始终是本地时间)

time.gmtime seconds since epoch——UTC中的>元组

and

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

time.localtime 自epoch ->元组在本地时区的秒数