使用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) >>> # 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) >>> # 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 >>>
希望能帮助到你。