在Python中使用strftime()与%f获取微秒
我正在尝试使用strftime()来获取微秒级的时间,这似乎可以通过使用%f来实现(具体可以参考这里)。但是当我尝试以下代码时:
import time
import strftime from time
print strftime("%H:%M:%S.%f")
...我得到了小时、分钟和秒,但%f却显示为%f,根本没有微秒的显示。我在Ubuntu上运行的是Python 2.6.5,所以应该没问题,%f应该是支持的(据我所知,2.6及以上版本都是支持的)。
8 个回答
16
在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
>>>
228
你可以使用datetime里的strftime函数来实现这个功能。问题是,time的strftime函数接受的时间元组不包含微秒的信息。
from datetime import datetime
datetime.now().strftime("%H:%M:%S.%f")
这样做就可以了!