如何在 python 3.5 中以毫秒而不是微秒获取日期时间的 ISO8601 字符串

问题描述 投票:0回答:2

给定以下日期时间:

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 来获取微秒,没有毫秒的占位符。

python python-3.x datetime python-3.5 iso8601
2个回答
14
投票

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

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'
所以你应该 shim 这个:

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'

0
投票

3.10(也可能更早),你可以在单班机上完成

>>> now = datetime.datetime.now()
>>> tz = datetime.timezone(datetime.timedelta(hours=-6), name="CST")
>>> now_tz = now.replace(tzinfo=tz)
>>> now_tz.isoformat("#","milliseconds")
'2023-03-02#11:02:07.592-06:00'
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.