I have two strings containing a date like so"
start_date = 'Sun Sep 16 16:05:15 +0000 2012'
end_date = 'Sun Sep 17 23:55:20 +0000 2012'
I need to perform: end_date - start_date
It should return the number of seconds separating the end and start dates.
This data is extracted from the twitter api. This is what the json gives me. Since it seems like a commonly used string, I assume there's a library or method that can handle this. I'm just not able to find one. Thanks!
Python comes with an inbuilt datetime module that helps us to solve various datetime related problems. In order to find the difference between two dates we simply input the two dates with date type and subtract them, which in turn provides us the number of days between the two dates.
timedelta() method. To find the difference between two dates in Python, one can use the timedelta class which is present in the datetime library. The timedelta class stores the difference between two datetime objects.
You can subtract a day from a python date using the timedelta object. You need to create a timedelta object with the amount of time you want to subtract. Then subtract it from the date.
Here is the full answer:
from datetime import datetime
start_date = 'Sun Sep 16 16:05:15 +0000 2012'
end_date = 'Sun Sep 17 23:55:20 +0000 2012'
def __datetime(date_str):
return datetime.strptime(date_str, '%a %b %d %H:%M:%S +0000 %Y')
start = __datetime(start_date)
end = __datetime(end_date)
delta = end - start
print delta # prints: 1 day, 7:50:05
print delta.total_seconds() # prints: 114605.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With