Python 3如何将格式转换为yyyy-mm-ddThh:mm:ssZ

13
我是Python的新手,但就算我在网上找了很久也无法找到我需要的答案。我需要将时间戳格式化为这样的格式:包括'T'、'Z',没有子秒或毫秒,就像这样yyyy-mm-ddThh:mm:ssZ,例如2019-03-06T11:22:00Z。有很多关于解析此格式的内容,但没有关于此方式格式化的内容。我已经尝试过使用arrow并阅读了他们的文档,但无法使其正常工作。如果有帮助,将不胜感激。

请提供一个带有期望输出的输入,以及您尝试过的内容。 - DirtyBit
我认为这将解决你的问题。 - Aman Jaiswal
可能是Python从字符串获取日期的重复问题。 - DirtyBit
这个回答解决了你的问题吗?如何将Python datetime转换为可读格式日期的字符串? - questionto42
4个回答

28

尝试使用 datetime

import datetime

output_date = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
print(output_date)

更多信息请参见Python文档


谢谢,我已经尝试过了,但是它给了我毫秒或亚秒,而我需要去掉亚秒,但是在尝试了你给我的代码后,我终于让它工作了 :) date = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ") print(date) - ra67052

16

请注意,仅仅因为一个日期的格式看起来像是UTC,并不意味着它是准确的。

在ISO 8601中,“Z”代表“zulu时间”或UTC(“+00:00”)。而当地时间通常由其与UTC的偏移量来表示。更糟糕的是,这些偏移量可能会因夏令时而在一年中发生变化。

因此,除非您在冬季生活在英格兰或夏季生活在冰岛,否则您很可能没有幸运地在本地使用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'

我只是想说明一些事情,其实有更简单的方法:

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)


谢谢,我没有想到过这一点,幸运的是应用程序在协调世界时运行,以解决夏令时问题,JSON接口消息中指定了使用“Z”,因此我们不得不使用它。然而,这篇文章非常有见地,我会记在心里。 - ra67052
@Sam:我有类似的需求,请问您能否建议我们如何考虑夏令时的启用和关闭。 - Gaurav Parek

2
感谢skaul05,我成功得到了所需的代码,它是最初的回答
date = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
print(date)

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接