Integer difference in python between two dates

Question:

I’ve RTFM and read many questions and answers here on SO regarding this, and was happily using strftime and strptime yesterday, so I would swear this should work, but it isn’t….

I just want an integer. Not a “timedelta object.” Not an “aware yet hashable object” (see, I RTFM). Not a tuple. Not a dictionary. Just a simple freaking integer so I can use an if statement and branch and be happy. Please bring the light of your wisdom upon this, with thanks.

Here’s what I have

...
import datetime
mdate = "2010-10-05"
rdate = "2010-10-05"
mdate1 = datetime.strptime(mdate, "%Y-%m-%d")
rdate1 = datetime.strptime(rdate, "%Y-%m-%d")
delta =  datetime.timedelta.days(mdate1 - rdate1)

Here’s what I get:

pmain.py:4: AttributeError: 'module' object has no attribute 'strptime'
(error hits in the 'mdate1..." line above)

And, that doesn’t mean that my delta line is going to work — please look at that one, too.

Asked By: Todd Curry

||

Answers:

You want to get the classmethod datetime.datetime.strptime(), then take the .days attribute from the resulting timedelta:

import datetime

mdate = "2010-10-05"
rdate = "2010-10-05"
mdate1 = datetime.datetime.strptime(mdate, "%Y-%m-%d").date()
rdate1 = datetime.datetime.strptime(rdate, "%Y-%m-%d").date()
delta =  (mdate1 - rdate1).days

So you have the datetime module, which has a datetime.datetime class, which in turn has a datetime.datetime.strptime() method on it. I also added calls to .date() to extract just the date portion (result is a datetime.date instance); this makes dealing with timestamps that differ slightly less than a multiple of 24 hours easier.

Demo:

>>> import datetime
>>> mdate = "2010-10-05"
>>> rdate = "2010-10-05"
>>> mdate1 = datetime.datetime.strptime(mdate, "%Y-%m-%d").date()
>>> rdate1 = datetime.datetime.strptime(rdate, "%Y-%m-%d").date()
>>> delta =  (mdate1 - rdate1).days
>>> print delta
0
>>> type(delta)
<type 'int'>
Answered By: Martijn Pieters
sign1['days'] = sign1['diff'] / np.timedelta64(1, 'D')

I had the same problem and it solved by uding the above statement.
I hope it helps.

Answered By: shilpa.rpns
import datetime
mdate = "2010-11-05"
rdate = "2010-10-05"
mdate1 = datetime.datetime.strptime(mdate, "%Y-%m-%d")
rdate1 = datetime.datetime.strptime(rdate, "%Y-%m-%d")
delta = (mdate1 - rdate1).days
Answered By: PLABON DATTA
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.