我正在使用以下方法打印时间戳:
strftime('%d-%m-%Y %H:%M:%S.%f')但是,我想把微秒舍入小数点后的两位,而不是打印到小数点后的六位。是否有更简单的方法来实现这一点,而不是“解压”所有的时间元素,格式化和舍入微秒到2小数点,以及格式化一个新的‘打印字符串’?
发布于 2014-10-27 12:01:32
decimal_places = 2
ndigits = decimal_places - 6
assert ndigits < 0
d = d.replace(microsecond=round(d.microsecond, ndigits))
print(d.strftime('%d-%m-%Y %H:%M:%S.%f')[:ndigits])
# -> 2014-10-27 11:59:53.87发布于 2014-10-27 11:57:23
您将不得不舍入自己;使用字符串格式设置日期的格式,不需要微秒,然后分别添加microsecond属性的前两位数:
'{:%d-%m-%Y %H:%M:%S}.{:02.0f}'.format(dt, dt.microsecond / 10000.0)演示:
>>> from datetime import datetime
>>> dt = datetime.now()
>>> '{:%d-%m-%Y %H:%M:%S}.{:02.0f}'.format(dt, dt.microsecond / 10000.0)
'27-10-2014 11:56:32.72'发布于 2018-09-07 04:47:45
基于jfs的回答,我又添加了一条语句作为
replace(microsecond=round(d.microsecond, ndigits))
可能会出现错误: ValueError: microsecond必须在0.999999中。
也就是说,如果微秒为995000到999999圆(微秒,数字),则为1000000。
d = datetime.utcfromtimestamp(time.time())
decimal_places = 2
ndigits = decimal_places - 6
r = round(d.microsecond, ndigits)
if r > 999999:
r = 999999
d = d.replace(microsecond=r)
ts = d.strftime('%Y-%m-%dT%H:%M:%S.%f')[:ndigits]https://stackoverflow.com/questions/26586943
复制相似问题