2

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MichaelJohn
  • 185
  • 3
  • 15

3 Answers3

4

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'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1
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
jfs
  • 399,953
  • 195
  • 994
  • 1,670
1

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]
Evan
  • 1,152
  • 1
  • 11
  • 18