Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the difference between two datetime objects in minutes in python

I have two datetime objects created by strptime in Python:

date_string = "Wed, 18 Dec 2013 09:30:00 GMT"
date = datetime.datetime.strptime(date_string, "%a, %d %b %Y %H:%M:%S %Z")

and

end_date_string = "Wed, 18 Dec 2013 10:15:00 GMT"
end_date = datetime.datetime.strptime(end_date_string, "%a, %d %b %Y %H:%M:%S %Z")

Datetime objects are created successfully so i get

>>>date
datetime.datetime(2013, 12, 18, 9, 30)
>>>end_date
datetime.datetime(2013, 12, 18, 10, 15)

I want to count the minutes the two datetimes differ. I do

diff = end_date - date   

and i get

 datetime.timedelta(0)

So it says that they are the same dates?No difference at all? Also seconds property is zero

>>>diff.seconds
0

How can this be made to work?

like image 433
Apostolos Avatar asked Feb 14 '23 08:02

Apostolos


2 Answers

import datetime

date_string = "Wed, 18 Dec 2013 09:30:00 GMT"
date = datetime.datetime.strptime(date_string, "%a, %d %b %Y %H:%M:%S %Z")
end_date_string = "Wed, 18 Dec 2013 10:15:00 GMT"
end_date = datetime.datetime.strptime(end_date_string, "%a, %d %b %Y %H:%M:%S %Z")
print (end_date-date).total_seconds()

Gives

2700.0
like image 100
Andrew Walker Avatar answered Feb 17 '23 01:02

Andrew Walker


it's kinda weird, i get the correct result:

>>> date_string = "Wed, 18 Dec 2013 09:30:00 GMT"
>>> date = datetime.datetime.strptime(date_string, "%a, %d %b %Y %H:%M:%S %Z")
>>> end_date_string = "Wed, 18 Dec 2013 10:15:00 GMT"
>>> end_date = datetime.datetime.strptime(end_date_string, "%a, %d %b %Y %H:%M:%S %Z")
>>> diff = end_date - date
>>> diff
datetime.timedelta(0, 2700)
>>> diff.seconds
2700

is this the whole code?

like image 39
6160 Avatar answered Feb 17 '23 02:02

6160