我想使用strftime()函数以微秒精度输出时间,这似乎可以通过使用 %f 实现(正如 这里 所述)。然而,当我尝试运行以下代码时:
import time
import strftime from time
print strftime("%H:%M:%S.%f")
我可以得到小时,分钟和秒数,但%f的输出只有%f,没有微秒的迹象。我在Ubuntu上运行Python 2.6.5,所以应该没问题,%f也应该被支持(据我所知,它适用于2.6及以上版本)。
from datetime import datetime
datetime.now().strftime("%H:%M:%S.%f")
应该可以解决问题!
使用Python的time
模块无法通过%f
获取微秒。
对于仍想仅使用time
模块的人,这里有个解决方法:
now = time.time()
mlsec = repr(now).split('.')[1][:3]
print time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), time.localtime(now))
你应该会得到类似于2017-01-16 16:42:34.625 EET 的结果(是的, 我使用毫秒,因为它足够精确)。
若要详细了解代码,请将以下代码复制并粘贴到Python控制台中:
import time
# Get current timestamp
now = time.time()
# Debug now
now
print now
type(now)
# Debug strf time
struct_now = time.localtime(now)
print struct_now
type(struct_now)
# Print nicely formatted date
print time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)
# Get miliseconds
mlsec = repr(now).split('.')[1][:3]
print mlsec
# Get your required timestamp string
timestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)
print timestamp
为了澄清,我在这里也贴出了我的Python 2.7.12的结果:
>>> import time
>>> # get current timestamp
... now = time.time()
>>> # debug now
... now
1484578293.519106
>>> print now
1484578293.52
>>> type(now)
<type 'float'>
>>> # debug strf time
... struct_now = time.localtime(now)
>>> print struct_now
time.struct_time(tm_year=2017, tm_mon=1, tm_mday=16, tm_hour=16, tm_min=51, tm_sec=33, tm_wday=0, tm_yday=16, tm_isdst=0)
>>> type(struct_now)
<type 'time.struct_time'>
>>> # print nicely formatted date
... print time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)
2017-01-16 16:51:33 EET
>>> # get miliseconds
... mlsec = repr(now).split('.')[1][:3]
>>> print mlsec
519
>>> # get your required timestamp string
... timestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)
>>> print timestamp
2017-01-16 16:51:33.519 EET
>>>
import datetime
datetime.datetime.now().strftime("%H:%M:%S.%f")
HH:MM:SS.毫秒数
,例如:14:38:19.425961
。使用 time
模块的 time()
函数,您还可以获得微秒精度。
(time.time()
返回自纪元以来的秒数。它的小数部分是微秒时间,这就是您想要的。)
>>> from time import time
>>> time()
... 1310554308.287459 # the fractional part is what you want.
# comparision with strftime -
>>> from datetime import datetime
>>> from time import time
>>> datetime.now().strftime("%f"), time()
... ('287389', 1310554310.287459)
当微秒的"%f"无法使用时,请使用以下方法:
import datetime
def getTimeStamp():
dt = datetime.datetime.now()
return dt.strftime("%Y%j%H%M%S") + str(dt.microsecond)
import datetime
print(datetime.datetime.now().strftime("%s%f")[:13])
输出:
1545474382803
def _timestamp(prec=0):
t = time.time()
s = time.strftime("%H:%M:%S", time.localtime(t))
if prec > 0:
s += ("%.9f" % (t % 1,))[1:2+prec]
return s
prec
是精度 -- 您想要多少小数位。
请注意,此函数不会像其他在此处提供的解决方案一样,在小数部分中存在前导零的问题。
datetime
支持%z
指令,而 time 似乎不支持。 - adamnfish%z
:-) 这是datetime和time - adamnfishfrom datetime import datetime
。如果只使用import datetime
,则需要使用datetime.datetime.now().strftime("%H:%M:%S.%f")
。 - JBaczuk