将日期转换为精度有限的字符串

时间:2012-06-28 17:00:56

标签: python

我在此日期使用dateString = date.strftime('%Y-%m-%d %H:%M:%S.%f')2012-06-28 16:11:17返回2012-06-28 16:11:17.999771,由于某种原因,它由Objective-c无法解析。如何将字符串的最后部分限制为3位小数而不是6?

2 个答案:

答案 0 :(得分:3)

使用:

date.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

这是slicing(语法[from:to(but but include):step]):

>>> '123456'[:-3]
'123'
>>> '123456'[3:]
'456'
>>> '123456'[1:-1]
'2345'
>>> '123456'[::2]
'135'
>>> '123456'[::-1]
'654321'
>>> '123456'[-2::]
'56'

答案 1 :(得分:0)

[:-3]方法失去了精确度,即'17.999771'[:-3] -> '17.999',但它应该是18.000

要正确舍入时间convert datetime object to seconds,将它们四舍五入并转换回来。 e.g:

from datetime import datetime

dt = datetime(2012, 6, 28, 16, 11, 17, 999771)


secs = (dt - datetime(1970, 1, 1)).total_seconds()
dt = datetime.utcfromtimestamp(round(secs, 3)) # round to thousands
print dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
# -> '2012-06-28 16:11:18.000'