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

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

问题描述

我正在使用以下命令打印时间戳记:

I am using the following to print out timestamps:

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

但是我想将微秒四舍五入到小数点后两位而不是打印到小数点后六位。有没有一种简单的方法可以实现此目的,而不是将所有时间元素都拆包,将微秒格式化并四舍五入为小数点后两位和格式化新的打印字符串?

However I want to round the microseconds to two decimal places rather than print out to six 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

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

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