我希望输出:
"14:48:06.743174"
Run Code Online (Sandbox Code Playgroud)
这是我能得到的最接近的:
`"14:48:06"`
Run Code Online (Sandbox Code Playgroud)
有:
t = time.time()
time.strftime("%H:%M:%S",time.gmtime(t))
Run Code Online (Sandbox Code Playgroud)
根据手册,time没有直接的方式来打印微秒(或浮点数秒):
>>> time.strftime("%H:%M:%S.%f",time.gmtime(t))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Invalid format string
Run Code Online (Sandbox Code Playgroud)
但datetime.datetime格式提供%f的定义为:
Microsecond为十进制数[0,999999],左侧为零填充
>>> import datetime
>>> datetime.datetime.now().strftime('%H:%M:%S.%f')
'14:07:11.286000'
Run Code Online (Sandbox Code Playgroud)
或者当您存储了您的值时t = time.time(),您可以使用datetime.datetime.utcfromtimestam():
>>> datetime.datetime.utcfromtimestamp(t).strftime('%H:%M:%S.%f')
'12:08:32.463000'
Run Code Online (Sandbox Code Playgroud)
我担心如果你想要更多地控制微秒的格式化(例如只显示3个地方而不是6个)你将要么裁剪文本(使用[:-3]):
>>> datetime.datetime.utcfromtimestamp(t).strftime('%H:%M:%S.%f')[:-3]
'12:08:32.463'
Run Code Online (Sandbox Code Playgroud)
或手动格式化:
>>> '.{:03}'.format(int(dt.microsecond/1000))
'.463'
Run Code Online (Sandbox Code Playgroud)