Formatting microseconds to two decimal places (in

2020-02-13 03:28发布

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'?

3条回答
神经病院院长
2楼-- · 2020-02-13 03:39

Based on jfs' answer, I added one more statement as

replace(microsecond=round(d.microsecond, ndigits))

may give an error : ValueError: microsecond must be in 0..999999.

i.e. if microsecond is from 995000 to 999999 round(microsecond, ndigits) will give 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]
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-02-13 03:41
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
查看更多
Melony?
4楼-- · 2020-02-13 04:02

You'll have to round yourself; use string formatting to format the date without microseconds, then add in the top two digits of the microsecond attribute separately:

'{:%d-%m-%Y %H:%M:%S}.{:02.0f}'.format(dt, dt.microsecond / 10000.0)

Demo:

>>> 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'
查看更多
登录 后发表回答