Python integer difference between two dates

I have RTFM and I read a lot of questions and answers here about this and was happy to use strftime and strptime yesterday, so I would have sworn that this should work, but it is not.

I just want an integer. Not a "timedelta object". Not a "hash aware yet object" (see I RTFM). Not a motorcade. Not a dictionary. Just a prime integer, so I can use the if statement and the branch and be happy. Please bring the light of your wisdom, thank you.

That's what i

... 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 is what I get:

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

And this does not mean that my delta line will work - please look at this one too.

+10
source share
3 answers

You want to get classmethod datetime.datetime.strptime() , then take the .days attribute from received 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 a datetime module that has a datetime.datetime class, which in turn has a datetime.datetime.strptime() method on it. I also added calls to .date() to extract only a portion of the date (the result is an instance of datetime.date ); this allows you to cope with timestamps that differ by a little less than 24 hours.

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'> 
+26
source
 sign1['days'] = sign1['diff'] / np.timedelta64(1, 'D') 

I had the same problem and it was resolved using the above statement. I hope this helps.

0
source

thank you very much for working. Can be applied to data frames.

0
source

Source: https://habr.com/ru/post/943439/


All Articles