1

I am trying to find the difference between two times in Python. It is guaranteed that the times are on the same day.

#For example
s1 = '13:00' 
s2 = '12:58'

The difference between these two times should be 2 mins. The output should be: 2

This is my code:

from datetime import datetime
s1 = '13:00'
s2 = '12:58'
FMT = '%H:%M'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
print(tdelta)

But it returns:

-1 day, 23:58:00

How can i fix this and return my time as: 2

Mahir Islam
  • 1,941
  • 2
  • 12
  • 33

2 Answers2

3

You can try using abs for the result i.e. abs(datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)):

from datetime import datetime
s1 = '13:00'
s2 = '12:58'
FMT = '%H:%M'
tdelta = abs(datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT))
print(tdelta)

Result:

0:02:00

Update:

As suggested in comment below, if you specifically want difference in minutes, you can use .total_seconds()/60 in tdelta:

from datetime import datetime
s1 = '13:00'
s2 = '12:58'
FMT = '%H:%M'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
minutes_difference = abs(tdelta.total_seconds()/60)
print(minutes_difference)

Result:

2.0
Community
  • 1
  • 1
niraj
  • 17,498
  • 4
  • 33
  • 48
  • 1
    Difference in minutes: [timedelta.total_seconds()](https://docs.python.org/3.6/library/datetime.html#datetime.timedelta.total_seconds) / 60 – wwii Jun 03 '18 at 15:40
0

You could use the Python pandas library:

import pandas as pd

time_1 = pd.Timestamp('13:00')
time_2 = pd.Timestamp('12:58')
delta = time_1 - time_2
print(delta)

The Timestamp() method will allow you to create a simple Timestamp. Here is your output:

0 days 00:02:00

It takes as a given that the Timestamps are on the same day unless you specify otherwise.

Simeon Ikudabo
  • 2,152
  • 1
  • 10
  • 27