2

I have something like this:

import datetime

a = datetime.datetime.now()
do_something_for_a_long_time()
b = datetime.datetime.now()
c = b - a

print("Doing <something> took {c}".format(c))

The problem is that this works well but we want the seconds value to be in the form ., not microseconds?

I was able to isolate the milliseconds attribute from that timedelta object, it it seems it only has microseconds available.

A R
  • 500
  • 2
  • 7
  • 20
  • 1
    Then why don’t you compute the millis from the micros? – Jens Dec 22 '20 at 05:33
  • By dividing the micros by 1000 and then appending the value? Wouldn't I lose accuracy over time? – A R Dec 22 '20 at 05:35
  • I think you already agreed to a loss of precision by saying that you want to use millis instead of micros. Take a look at how [Python rounds numbers](https://docs.python.org/3/library/functions.html#round) for more details. – Jens Dec 22 '20 at 20:35

2 Answers2

3

Given your initial code example, you could use something like this:

# From your example.
c = b - a

# Get the hours, minutes, and seconds.
minutes, seconds = divmod(c.seconds, 60)
hours, minutes = divmod(minutes, 60)

# Round the microseconds to millis.
millis = round(c.microseconds/1000, 0)

print(f"Doing <something> took {hours}:{minutes:02}:{seconds:02}.{millis}")

which results in

# c = datetime.timedelta(seconds=7, microseconds=319673)
Doing <something> took 0:00:07.320

Take a look at Python’s built-in functions round() and divmod() and please poke around this and this related thread; also, please read through this and this thread to learn more about formatting timedelta objects.

Jens
  • 8,423
  • 9
  • 58
  • 78
-2

just chop off the last three digits of the microseconds if you don't want to manually round off:

def format_time():
t = datetime.datetime.now()
s = t.strftime('%Y-%m-%d %H:%M:%S.%f')
return s[:-3] `def format_time():
t = datetime.datetime.now()
s = t.strftime('%Y-%m-%d %H:%M:%S.%f')
return s[:-3]
  • the object I'm trying to convert is a timedelta, it doesn't have strftime. Also, is it really ok to simply chop the numbers? Don't I have to divide by something first? – A R Dec 22 '20 at 16:42
  • Chopping off is not a good way of approaching this problem. As AR indicates, you can divide and call [round()](https://docs.python.org/3/library/functions.html#round), or take a look at related threads like [this one](https://stackoverflow.com/questions/14540143/python-3-float-decimal-points-precision). – Jens Dec 22 '20 at 20:38
  • Very well, I can do something like `t.microseconds`, then convert that value to milliseconds. Now, how do I stick than number back into the object so that a print statement gives me something like: 00:05:00. – A R Dec 22 '20 at 21:11
  • @AR, please see my answer below. – Jens Dec 22 '20 at 21:21