0

I have a string named "Time" which is "01:20:23 01:25:36" in the format min:second:millisecond.

I need to do a subtraction by using these two time values.

The result should be 00:05:13 (5 seconds and 13 milliseconds)

How can I do this in Python?

baduker
  • 19,152
  • 9
  • 33
  • 56
  • 1
    [Time difference in python](https://stackoverflow.com/questions/1345827/how-do-i-find-the-time-difference-between-two-datetime-objects-in-python) This might help – Morse Mar 07 '18 at 19:55
  • 1
    Welcome to StackOverflow. Have you tried any approach that failed so far? If so, please consider adding your existing code so that other users can help you get to the answer. – goncalotomas Mar 07 '18 at 20:05

2 Answers2

5

Using datetime:

from datetime import datetime

time1, time2 = [datetime.strptime(x, '%M:%S:%f') for x in "01:20:23 01:25:36".split()]
print(time2 - time1)

Output:

0:00:05.130000

I had to use '%M:%S:%f' (notice the colon between seconds and milliseconds) to represent minutes, seconds, and milliseconds to make your example input work, although it is usually represented %M:%S.%f. Just something to think about when making these strings.

user3483203
  • 50,081
  • 9
  • 65
  • 94
  • I think the OP needs the answer 5 seconds and 13 miliseconds, your answer, reading it carefully, is 5 seconds and 130 miliseconds, or 130000 microseconds – DSLima90 Mar 07 '18 at 20:05
  • If he needs that answer he is subtracting the wrong two times ;) – user3483203 Mar 07 '18 at 20:07
  • I dont think so, his code assumes 36 and 23 after ':' are raw millisecond values (36milliseconds, not 0.36 seconds for example), yours, with %f considers it to be 360000 and 230000 microseconds, or 360 and 230 miliseconds. – DSLima90 Mar 07 '18 at 20:14
  • Complementing, he assumes '01:20:23' as '01:20.023', not '01:20.23'. – DSLima90 Mar 07 '18 at 20:29
  • Good job, but how to get rid of 0: at the beginning and 000 at the end? what I need is the output DO NOT include these useless things. – playtrumps Mar 08 '18 at 02:33
0

You'll want to use a package that can handle time rather than write your own converter because of all the edge cases with time. Here, I use a dummy year and give both strings an actual day on which they occur.

import numpy as np
np.datetime64('2000-01-01T01:25:36') - np.datetime64('2000-01-01T01:20:23')

If you're doing this more than once with numbers exactly formatted as you gave them above:

mystring = "01:20:23 01:25:36"

# Split the string at the space
split = mystring.split(" ")

# Make two new strings 
header = "2000-01-01T"
np.datetime64(header+split[1]) - np.datetime64(header+split[0])
Seth Rothschild
  • 384
  • 1
  • 14