在Python中使用%f与strftime()来获得微秒

我试图使用strftime()以微秒精度,这似乎可能使用%f(如此处所述)。 但是,当我尝试下面的代码:

import time import strftime from time print strftime("%H:%M:%S.%f") 

…我得到小时,分钟和秒,但%f打印为%f,没有微秒的迹象。 我在Ubuntu上运行Python 2.6.5,所以应该没问题,应该支持%f(据我所知它支持2.6以上)。

你可以使用datetime的strftime函数来获得这个。 问题是,时间的strftime接受一个不带微秒信息的时间。

 from datetime import datetime datetime.now().strftime("%H:%M:%S.%f") 

应该做的伎俩!

您正在查看错误的文档。 time模块有不同的文档 。

你可以像这样使用datetime模块strftime

 >>> from datetime import datetime >>> >>> now = datetime.now() >>> now.strftime("%H:%M:%S.%f") '12:19:40.948000' 

您也可以使用time()函数从time模块中获取微秒精度。
time.time()返回从epoch开始的以秒为单位的时间,它的小数部分是以微秒为单位的时间,这就是你想要的。

 >>> 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) 

这应该做的工作

 import datetime datetime.datetime.now().strftime("%H:%M:%S.%f") 

它会打印

HH:MM:SS.microseconds like this,eg 14:38:19.425961

当微秒的“%f”不工作时,请使用以下方法

 import datetime def getTimeStamp(): dt = datetime.datetime.now() return dt.strftime("%Y%j%H%M%S") + str(dt.microsecond) 

使用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 >>> 

希望能帮助到你。