将微秒格式化为2位小数(实际上将微秒转换为几十微秒) [英] Formatting microseconds to 2 decimal places ( in fact converting microseconds into tens of microseconds )

查看:306
本文介绍了将微秒格式化为2位小数(实际上将微秒转换为几十微秒)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下内容打印时间戳:

I am using the following to print out timestamps:

strftime('%d-%m-%Y %H:%M:%S.%f')

然而,我想将微秒舍入为2位小数而不是打印到小数点后6位。有没有更简单的方法来实现这一点,而不是拆包所有的时间元素,格式化和舍入微秒到2位小数,并格式化一个新的打印字符串?

However I want to round the microseconds to 2 decimal places rather than print out to 6 decimal places. Is there an easier way to achieve this rather than 'unpacking' all the time elements, formatting and rounding the microseconds to 2 decimals, and formatting a new 'print string'?

推荐答案

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

这篇关于将微秒格式化为2位小数(实际上将微秒转换为几十微秒)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆