Difference between two dates

Cédric Lucantis omer at no-log.org
Tue Jun 24 06:31:52 EDT 2008


Le Tuesday 24 June 2008 12:11:03 sniipe at gmail.com, vous avez écrit :
> Hi!
>
> I am new in Python, so I count for your help. I need to get difference
> in months between two dates. How to do it in python? I am substracting
> two dates, for example date1 - date2 and I got result in days, how to
> change it?
>

Maybe the datetime and calendar modules may help too, but a simple solution is 
to get your dates in number of months (tm1 and tm2 being struct_time objects 
returned by time.localtime/gmtime) :

m1 = tm1.tm_year * 12 + (tm1.tm_mon - 1)
m2 = tm2.tm_year * 12 + (tm2.tm_mon - 1)

then (m1 - m2) gives the difference in months

(see the time modules docs for more infos)

-- 
Cédric Lucantis



More information about the Python-list mailing list