【问题标题】:Python 3 How to format to yyyy-mm-ddThh:mm:ssZPython 3 如何格式化为 yyyy-mm-ddThh:mm:ssZ
【发布时间】:2019-07-28 01:15:26
【问题描述】:

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

【问题讨论】:

标签: python datetime format arrow-python


【解决方案1】:

试试datetime

import datetime

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

有关详细信息,请参阅Python Documentation

【讨论】:

  • 谢谢,我已经尝试过了,但这给了我毫秒或亚秒,我需要删除亚秒,但是弄乱了你给我的代码,我让它工作:) date = datetime .datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ") 打印(日期)
【解决方案2】:

感谢 skaul05,我设法得到了我需要的代码,它是

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

【讨论】:

    【解决方案3】:

    小心。只是因为日期可以被格式化为 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'
    

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

    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)
    
    

    【讨论】:

    • 谢谢,没想到这一点,谢天谢地,应用程序在 UTC 上运行以解决夏令时问题,JSON 的接口消息中指定了“Z”的使用,因此我们为什么不得不使用它。不过,这篇文章很有见地,我会把它放在我的口袋里。
    • @Sam:我也有类似的要求,请您告诉我们如何考虑开启和关闭夏令时。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 2018-05-06
    • 2022-09-22
    相关资源
    最近更新 更多