【问题标题】:How to get ISO8601 string for datetime with milliseconds instead of microseconds in python 3.5如何在python 3.5中以毫秒而不是微秒获取日期时间的ISO8601字符串
【发布时间】:2019-03-27 09:42:11
【问题描述】:

给定以下日期时间:

d = datetime.datetime(2018, 10, 9, 8, 19, 16, 999578, tzinfo=dateutil.tz.tzoffset(None, 7200))

d.isoformat() 生成字符串:

'2018-10-09T08:19:16.999578+02:00'

如何获取毫秒而不是微秒的字符串:

'2018-10-09T08:19:16.999+02:00'

strftime() 在这里不起作用:%z 返回 0200 而不是 02:00,并且只有 %f 来获取微秒,毫秒没有占位符。

【问题讨论】:

  • strftime(): %z 返回 0200 而不是 02:00 并且只有 %f 获取微秒,没有毫秒的占位符。
  • 将 datetime 对象中的时间数据格式化为字符串仍在使用 str.format(),如果您可以从 datetime 对象中获取微秒和毫秒,您可以以 str.format 可以做的任何方式格式化字符串表示。 strftime() 正是为此提供的方法。

标签: python python-3.x datetime python-3.5 iso8601


【解决方案1】:

如果没有冒号的时区是可以的,你可以使用

d = datetime.datetime(2018, 10, 9, 8, 19, 16, 999578, 
                      tzinfo=dateutil.tz.tzoffset(None, 7200))
s = d.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + d.strftime('%z')
# '2018-10-09T08:19:16.999+0200'

对于冒号,您需要拆分时区并自行添加。 %z 也不为 UTC 生成 Z


Python 3.6 支持timespec='milliseconds',所以你应该填充这个:

try:
    datetime.datetime.now().isoformat(timespec='milliseconds')
    def milliseconds_timestamp(d):
        return d.isoformat(timespec='milliseconds')

except TypeError:
    def milliseconds_timestamp(d):
        z = d.strftime('%z')
        z = z[:3] + ':' + z[3:]
        return d.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + z

鉴于 Python 3.6 中的后者定义,

>>> milliseconds_timestamp(d) == d.isoformat(timespec='milliseconds')
True

>>> milliseconds_timestamp(d)
'2018-10-09T08:19:16.999+02:00'

【讨论】:

  • 冒号很重要,它必须与python 3.5一起运行。
  • @cytrinox 然后是我后面的摘录
猜你喜欢
  • 2012-02-12
  • 2013-03-03
  • 2015-12-20
  • 2022-10-19
  • 1970-01-01
  • 2016-02-29
  • 1970-01-01
  • 2018-12-22
  • 1970-01-01
相关资源
最近更新 更多