Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python subtracting two date strings

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!

like image 326
Amitash Avatar asked Nov 08 '12 16:11

Amitash


People also ask

Can we subtract two dates in python?

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.

How do you subtract two timestamps in python?

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.

How do I subtract days from a date in python?

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.


1 Answers

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
like image 120
sphere Avatar answered Oct 25 '22 18:10

sphere