Python - Time delta from string and now()
Question: I have spent some time trying to figure out how to get a time delta between
time values. The only issue is that one of the times was stored in a file. So
I have one string which is in essence `str(datetime.datetime.now())` and
`datetime.datetime.now()`.

Specifically, I am having issues getting a delta because one of the objects is
a datetime object and the other is a string.

I think the answer is that I need to get the string back in a datetime object
for the delta to work.

I have looked at some of the other Stack Overflow questions relating to this
including the following:

[Python - Date & Time Comparison using timestamps,
timedelta](http://stackoverflow.com/questions/12131766/python-date-time-
comparison-using-timestamps-timedelta)  
[Comparing a time delta in
python](http://stackoverflow.com/questions/2591845/comparing-a-time-delta-in-
python)  
[Convert string into datetime.time
object](http://stackoverflow.com/questions/14295673/convert-string-into-
datetime-time-object)  
[Converting string into
datetime](http://stackoverflow.com/questions/466345/converting-string-into-
datetime)  

Example code is as follows:

    
    
    f = open('date.txt', 'r+')
    line = f.readline()
    date = line[:26]
    now = datetime.datetime.now()   
    then = time.strptime(date)
    delta = now - then # This does not work
    

Can anyone tell me where I am going wrong?

For reference, the first 26 characters are acquired from the first line of the
file because this is how I am storing time e.g.

    
    
    f.write(str(datetime.datetime.now())
    

Which would write the following: 2014-01-05 13:09:42.348000


Answer: `time.strptime` returns a struct_time. `datetime.datetime.now()` returns a
`datetime` object. The two can not be subtracted directly.

Instead of `time.strptime` you could use `datetime.datetime.strptime`, which
returns a `datetime` object. Then you could subtract `now` and `then`.

For example,

    
    
    import datetime as DT
    now = DT.datetime.now()   
    then = DT.datetime.strptime('2014-1-2', '%Y-%m-%d')
    delta = now - then 
    print(delta)
    # 3 days, 8:17:14.428035
    

* * *

By the way, you need to supply a date format string to `time.strptime` or
`DT.datetime.strptime`.

    
    
    time.strptime(date)
    

should have raised a ValueError.

* * *

It looks like your date string is 26 characters long. That might mean you have
a date string like `'Fri, 10 Jun 2011 11:04:17 '`.

If that is true, you may want to parse it like this:

    
    
    then = DT.datetime.strptime('Fri, 10 Jun 2011 11:04:17 '.strip(), "%a, %d %b %Y %H:%M:%S")
    print(then)
    # 2011-06-10 11:04:17
    

There is a table describing the available directives (like `%Y`, `%m`, etc.)
[here](http://docs.python.org/2/library/datetime.html#strftime-and-strptime-
behavior).

