How to tell how many weeks apart two datetimes are?

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Jan 8 23:54:20 CET 2013


On 8 January 2013 22:50, MRAB <python at mrabarnett.plus.com> wrote:
> On 2013-01-08 21:22, Roy Smith wrote:
>>
>> How do you tell how many weeks apart two datetimes (t1 and t2) are?
>> The "obvious" solution would be:
>>
>> weeks = (t2 - t1) / timedelta(days=7)
>>
>> but that doesn't appear to be allowed.  Is there some fundamental
>> reason why timedelta division not supported?
>>
> Try this:
>
> weeks = (t2 - t1).days / 7

You beat me to it...

$ python
Python 2.7.3 (default, Sep 26 2012, 21:51:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dt1 = datetime.datetime.now()
>>> dt2 = dt1 - datetime.timedelta(days=8)
>>> (dt2 - dt1) / 7 > datetime.timedelta(days=14)
False


Oscar



More information about the Python-list mailing list