Python 3 如何格式化为 yyyy-mm-ddThh:mm:ssZ

ra6*_*052 5 python format datetime arrow-python

我是 Python 的新手,我一生都无法在网上找到我的具体答案。我需要将时间戳格式化为这种确切格式以包含“T”、“Z”,并且没有像这样的 yyyy-mm-ddThh:mm:ssZ 即 2019-03-06T11:22:00Z 的子或毫秒。有很多关于解析这种格式的东西,但没有关于这种格式的内容。我几乎让它工作的唯一方法涉及我不需要的亚秒。我试过使用箭头并阅读他们的文档,但无法获得任何工作。任何帮助,将不胜感激。

ska*_*l05 14

试试datetime图书馆

import datetime

output_date = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
print(output_date)
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅Python 文档


小智 7

当心。只是因为日期可以格式化为看起来像 UTC,并不意味着它是准确的。

在 ISO 8601 中,'Z' 表示“祖鲁时间”或 UTC('+00:00')。而本地时间通常由它们与 UTC 的偏移量指定。更糟糕的是,由于夏令时 (DST),这些偏移量可能会在一年中发生变化。

因此,除非您冬天住在英格兰或夏天住在冰岛,否则您很可能没有幸运地在本地使用 UTC,并且您的时间戳将完全错误。

Python3.8

from datetime import datetime, timezone

# a naive datetime representing local time
naive_dt = datetime.now()

# incorrect, local (MST) time made to look like UTC (very, very bad)
>>> naive_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
'2020-08-27T20:57:54Z'   # actual UTC == '2020-08-28T02:57:54Z'

# so we'll need an aware datetime (taking your timezone into consideration)
# NOTE: I imagine this works with DST, but I haven't verified

aware_dt = naive_dt.astimezone()

# correct, ISO-8601 (but not UTC)
>>> aware_dt.isoformat(timespec='seconds')
'2020-08-27T20:57:54-06:00'

# lets get the time in UTC
utc_dt = aware_dt.astimezone(timezone.utc)

# correct, ISO-8601 and UTC (but not in UTC format)
>>> utc_dt.isoformat(timespec='seconds')
'2020-08-28T02:57:54+00:00'

# correct, UTC format (this is what you asked for)
>>> date_str = utc_dt.isoformat(timespec='seconds')
>>> date_str.replace('+00:00', 'Z')
'2020-08-28T02:57:54Z'

# Perfect UTC format
>>> date_str = utc_dt.isoformat(timespec='milliseconds')
>>> date_str.replace('+00:00', 'Z')
'2020-08-28T02:57:54.640Z'
Run Code Online (Sandbox Code Playgroud)

我只是想说明上面的一些事情,还有更简单的方法:

from datetime import datetime, timezone


def utcformat(dt, timespec='milliseconds'):
    """convert datetime to string in UTC format (YYYY-mm-ddTHH:MM:SS.mmmZ)"""
    iso_str = dt.astimezone(timezone.utc).isoformat('T', timespec)
    return iso_str.replace('+00:00', 'Z')


def fromutcformat(utc_str, tz=None):
    iso_str = utc_str.replace('Z', '+00:00')
    return datetime.fromisoformat(iso_str).astimezone(tz)


now = datetime.now(tz=timezone.utc)

# default with milliseconds ('2020-08-28T02:57:54.640Z')
print(utcformat(now))

# without milliseconds ('2020-08-28T02:57:54Z')
print(utcformat(now, timespec='seconds'))


>>> utc_str1 = '2020-08-28T04:35:35.455Z'
>>> dt = fromutcformat(utc_string)
>>> utc_str2 = utcformat(dt)
>>> utc_str1 == utc_str2
True

# it even converts naive local datetimes correctly (as of Python 3.8)
>>> now = datetime.now()
>>> utc_string = utcformat(now)

>>> converted = fromutcformat(utc_string)
>>> now.astimezone() - converted
timedelta(microseconds=997)

Run Code Online (Sandbox Code Playgroud)