datetime: How to get diff between 2 dates in month units?

python at sarcastic-horse.com python at sarcastic-horse.com
Fri Sep 12 22:19:12 CEST 2003


Hi-


I have a lot of monthly time series data.  I need to be able to compare
two dates and get the number of months that they are apart.

The datetime module is a daily-frequency data type.  It has a timedelta
object that returns the difference in days between two dates:

>>> d1 = datetime.date(2002,1,1)
>>> d2 = datetime.date(2001,12,1)
>>> diff = d1-d2
>>> diff.days
31

I want to be able to compare monthly-frequency data, so that I can do
something like this:

>>>firstdate = newMonthlyDatetime(2002, 5)
>>>Nov2002 = newMonthlyDatetime(2002, 11)
>>>diff = Nov2002 - firstdate
>>>diff.months
6

Does anyone have any suggestions about how to do something like this?

Thanks for the help.





More information about the Python-list mailing list