Search code examples
pythonstringsubtraction

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!


Solution

  • 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