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

python at sarcastic-horse.com python at sarcastic-horse.com
Mon Sep 15 11:19:07 EDT 2003


This is a great module.  Thanks for the link.  What do you think about
using operator overloading to avoid having to do the
mx.DateTime.RelativeDateDiff(...) function instead?






>> 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.
> [...]
>
> If you can rely on external modules, you may use mx.DateTime for that.
>
>> >>> d1 = datetime.date(2002,1,1)
>> >>> d2 = datetime.date(2001,12,1)
>> >>> diff = d1-d2
>> >>> diff.days
>> 31
>
> This would be:
>
>>>> d1 = DateTime.Date(2002,1,1)
>>>> d2 = DateTime.Date(2001,12,1)
>>>> diff = DateTime.RelativeDateDiff(d1,d2)
>>>> diff.months
> 1
>
> [...]
>> >>>firstdate = newMonthlyDatetime(2002, 5)
>> >>>Nov2002 = newMonthlyDatetime(2002, 11)
>> >>>diff = Nov2002 - firstdate
>> >>>diff.months
>> 6
>
> And this would be:
>
>>>> firstdate = DateTime.Date(2002, 5)
>>>> Nov2002 = DateTime.Date(2002, 11)
>>>> diff = DateTime.RelativeDateDiff(Nov2002, firstdate)
>>>> diff.months
> 6
>
> --
> Gustavo Niemeyer
> http://niemeyer.net
>






More information about the Python-list mailing list