0

On this problem I keep getting stuck when trying several options provided.

In simple words, I'm running a script that has a starting time (several actually, based on different criteria) and in a loop I want to display the running time of that criteria in a JSON and put it in a program (using requests) that is updated every time the loop passes one of the criteria.

I was doing that by simply running:

starting_time = datetime.now() #but just a bit earlier in the script
now = datetime.now()
running_time = now-starting_time

This running_time is then used as a variable in a JSON, but that needs to be in the format of 'HH:MM:SS' else my requests doesn't allow me to put. Which caused the problem for me, because it isn't possible to use strftime on a timedelta.

The timedelta might be based on miliseconds, but those are fine as "00:00:00"... but that caused me problems when trying to convert the timedelta to string first and then convert it back to a regular datetime.

What am I missing?

halfer
  • 19,824
  • 17
  • 99
  • 186
JeBo
  • 187
  • 1
  • 3
  • 12
  • Adding or subtracting 2 datetime objects returns a timedelta-object. To format a timedelta-object see https://stackoverflow.com/q/538666/2166778 – elMeroMero Mar 20 '20 at 22:13
  • Unfortunately the solution there --> str(timedelta) doesn't work, because after using datetime.strptime on that it doesn't work when the timedelta = 00:00:00.001001 --> ValueError: unconverted data remains: .001001 – JeBo Mar 20 '20 at 22:18

1 Answers1

1

A possible workaround would be:

starting_time = datetime.now()
now = datetime.now()
running_time = now-starting_time
x = datetime.timedelta(seconds=running_time.seconds)
result = str(x)
if result[1] == ":":
    result = "0"+result
print(result)

Here line 4 makes sure that x only has the seconds and ignores the miliseconds of running_time. Then we add a zero at the beginning in case needed.

But also see comment to better understand timedelta.

elMeroMero
  • 752
  • 6
  • 18
  • Thanks for your response! When I now use strptime(result) it adds 1900-01-01 infront of the time, is that common? --> datetime.strptime(result, "%H:%M:%S") – JeBo Mar 20 '20 at 22:48
  • why do you need strptime? The variable result returns the what you need in HH:MM:SS format, doesn't it? – elMeroMero Mar 21 '20 at 21:35