cyt*_*nox 6 python datetime iso8601 python-3.x python-3.5
鉴于以下日期时间:
d = datetime.datetime(2018, 10, 9, 8, 19, 16, 999578, tzinfo=dateutil.tz.tzoffset(None, 7200))
Run Code Online (Sandbox Code Playgroud)
d.isoformat() 结果为字符串:
'2018-10-09T08:19:16.999578+02:00'
Run Code Online (Sandbox Code Playgroud)
如何获得毫秒而不是微秒的字符串:
'2018-10-09T08:19:16.999+02:00'
Run Code Online (Sandbox Code Playgroud)
strftime() 在这里不起作用:%z 返回 0200 而不是 02:00 并且只有 %f 来获取微秒,没有毫秒的占位符。
如果没有冒号的时区没问题,你可以使用
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'
Run Code Online (Sandbox Code Playgroud)
对于冒号,您需要拆分时区并自己添加到那里。%z不会Z为 UTC生成。
并且 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
Run Code Online (Sandbox Code Playgroud)
鉴于 Python 3.6 中的后一个定义,
>>> milliseconds_timestamp(d) == d.isoformat(timespec='milliseconds')
True
Run Code Online (Sandbox Code Playgroud)
和
>>> milliseconds_timestamp(d)
'2018-10-09T08:19:16.999+02:00'
Run Code Online (Sandbox Code Playgroud)