3

Running this

import time
import datetime

timenow = time.time()
timedifference = time.time() - timenow
timedifference = datetime.timedelta( seconds=timedifference )
print( "%s" % timedifference )

I got this:

0:00:00.000004

How can I format trimming the microseconds to 2 decimal digits using the deltatime object?

0:00:00.00

Related questions:

  1. Timedelta in hours,minutes,seconds,microseconds format
  2. Formatting microseconds to two decimal places (in fact converting microseconds into tens of microseconds)
Evandro Coan
  • 8,560
  • 11
  • 83
  • 144

4 Answers4

3

Convert the timedifference to a string with str(), then separate on either side of the decimal place with .split('.'). Then keep the first portion before the decimal place with [0]:

Your example with the only difference on the last line:

import time
import datetime

timenow = time.time()
timedifference = time.time() - timenow
timedifference = datetime.timedelta( seconds=timedifference )
print( "%s" % str(timedifference).split('.')[0] )

generates:

0:00:00
Marc Compere
  • 290
  • 4
  • 17
3

Another solution is to split the fractional part numerically and format it separately:

>>> seconds = 123.995
>>> isec, fsec = divmod(round(seconds*100), 100)
>>> "{}.{:02.0f}".format(timedelta(seconds=isec), fsec)
'0:02:04.00'

As you can see, this takes care of the rounding. It is also easy to adjust the output precision by changing 100 above to another power of 10 (and adjusting the format string):

def format_td(seconds, digits=2):
    isec, fsec = divmod(round(seconds*10**digits), 10**digits)
    return ("{}.{:0%d.0f}" % digits).format(timedelta(seconds=isec), fsec)
Seb
  • 4,422
  • 14
  • 23
  • This is good but I still get something like 1:00:20.30, while I want for example 01:00:20.30. I tried to apply `{:0>8}.{:02.0f}` but it fails. Also `{%H:%M:%S}.{02.0f}` not working. Can I write it correctly in a quick way? – Peter.k Apr 18 '23 at 18:10
  • @Peter.k The `{:0>8}.{:02.0f}` approach should work as long as you wrap `timedelta(seconds=isec)` with `str(...)`. – Seb Apr 18 '23 at 18:31
2

You'll have to format it yourself. A timedelta object contains days, seconds and microseconds so you'll have to do the math to convert to days/hours/min/sec/microsec and then format using python string.format. For your microsec, you'll want ((microsec+5000)/10000) to get the top two digits (the +5000 is for rounding).

GaryO
  • 5,873
  • 1
  • 36
  • 61
2

A bit late, but here's a 2021 answer with f-strings (modified from @Seb's original answer):

def format_td(seconds, digits=3):
    isec, fsec = divmod(round(seconds*10**digits), 10**digits)
    return f'{timedelta(seconds=isec)}.{fsec:0{digits}.0f}'
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53