datetime: How to get diff between 2 dates in month units?
Pettersen, Bjorn S
BjornPettersen at fairisaac.com
Fri Sep 12 17:50:53 EDT 2003
> From: python at sarcastic-horse.com [mailto:python at sarcastic-horse.com]
>
> 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?
No, but I do have one question..: would diff.months be valid given d1
and d2 above (which also contain a day part)?
If so, what would it be given the dates 3/1/2001 - 1/30/2001; i.e. is a
month 1/12 of a year, or until the same day next month (with special
rules for end-of-month)?
If you answer no to the first question then your very close to a (year *
100 + month) representation...
-- bjorn
(time series data is fun ;-)
More information about the Python-list
mailing list