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.
You can use simple date arithmetic to find the number of days between two dates in Python. Define the 2 dates between which you want to find the difference in days. Then subtract these dates to get a timedelta object and examine the day's property of this object to get the required result.
You can subtract a day from a python date using the timedelta object. You need to create a timedelta object with the amount of time you want to subtract. Then subtract it from the date.
Use df. dates1-df. dates2 to find the difference between the two dates and then convert the result in the form of months.
timedelta() function. Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.
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'>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With