1

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
Comparing a time delta in python
Convert string into datetime.time object
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

Community
  • 1
  • 1
Matt S
  • 33
  • 1
  • 6

3 Answers3

3

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.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

Try this:

import time
import datetime
d = datetime.datetime.now()
now  = time.mktime(d.timetuple())

And then apply the delta

Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
0

if you have the year,month,day of 'then' you may use:

year  = 2013
month = 1
day   = 1

now_date = datetime.datetime.now()
then_date = now_date.replace(year = year, month = month, day = day)

delta = now_date - then_date
idanshmu
  • 5,061
  • 6
  • 46
  • 92