0

I need to subtract one timestamp to another.

Here's how I do it:

t1 = data[3]
t2 = data[4]
d1 = datetime.strptime(str(t1), "%H:%M:%S.%f")
d2 = datetime.strptime(str(t2), "%H:%M:%S.%f")
print(d2-d1)

It works fine only if the format of t1 and t2 is always %H:%M:%S.%f, but in my case, data[3] and data[4] will return a random timestamp, wich will sometimes not always have %f in it. Because of this, python will raise the following error:

ValueError: time data '00:41:17' does not match format '%H:%M:%S.%f'

Therefore, how can I make t1 and t2 always have zeroes as %f even if there aren't? Thanks in advance.

spund3
  • 127
  • 6
  • You could check for existence of '.' in the string and either pad the value - e.g., t1+'.0' or use a more appropriate format – DarkKnight Oct 01 '22 at 15:23

1 Answers1

1

The most brutal thing to do would be to check for dot in the format:

t1_has_zeros = t1.find(".") > 0

And then parse accordingly. Pro tip - try to make sure that you have ISO-8601 formatted time - it will save you some headaches in parsing, so you could just call the native datetime.fromisoformat.

Lior Pollak
  • 3,362
  • 5
  • 27
  • 48