python time.strftime_时间 - 在Python中使用%f和strftime()来获得微秒

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

>>>

希望能帮助到你。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值