python - 将微秒格式化为小数点后两位(实际上是将微秒转换为几十微秒)

标签 python python-2.7 datetime

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

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

但是我想将微秒四舍五入到小数点后两位,而不是打印到小数点后六位。有没有比“解包”所有时间元素、格式化微秒并将其四舍五入到小数点后 2 位以及格式化新的“打印字符串”更简单的方法?

最佳答案

你必须把自己围起来;使用字符串格式格式化没有微秒的日期,然后分别在 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'

关于python - 将微秒格式化为小数点后两位(实际上是将微秒转换为几十微秒),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26586943/

相关文章:

python - 什么是 'local variable referenced before assignment'

python - 如何获取当前的python解释器路径

python - Google App Engine 和 Cloud SQL : Lost connection to MySQL server at 'reading initial communication packet' SQL 2nd Gen

python - 获取按列年份分组的索引值集

python - 在 Python 中交叉列表列表的最有效方法?

python-2.7 - urllib3.HTTPSConnectionPool 错误

eclipse - 在 Eclipse 中如何在注释中自动打印当前日期/时间?

python-3.x - (Python) 按 mongoDB 集合中存储为字符串的日期进行查询

datetime - 按月/年间隔汇总每日数据

python - 为什么 "Googletrans.Translator"突然停止工作?