[Tutor] Through a glass, darkly: the datetime module

Oscar Benjamin oscar.j.benjamin at gmail.com
Fri Oct 5 16:16:44 CEST 2012


On 5 October 2012 14:47, Richard D. Moores <rdmoores at gmail.com> wrote:
> I thought it would be useful to have a script that would tell me what
> the date n days from today would be. The docs
> (<http://docs.python.org/py3k/library/datetime.html#module-datetime>)
> seem to get me almost there. I can compute the number of days between
> 2 dates, and the number of days between a date and today:
>
> Python 3.2.3 (default, Apr 11 2012, 07:12:16) [MSC v.1500 64 bit (AMD64)]
>
> import time
> from datetime import date, timedelta
>>>> date1 = date(2001, 9, 11)
>>>> date1
> datetime.date(2001, 9, 11)
>>>> date2 = date(2003, 4, 15)
>>>> date2
> datetime.date(2003, 4, 15)
>>>> date2 - date1
> datetime.timedelta(581)
>>>> days_delta = date2 - date1
>>>> days_delta.days
> 581
>>>> today = date.today()
>>>>> today
> datetime.date(2012, 10, 5)
>>>> print(today)
> 2012-10-05
>>>> time_to_date = today - date1
>>>> time_to_date
> datetime.timedelta(4042)
>>>> print(time_to_date)
> 4042 days, 0:00:00
>>>> print(time_to_date.days)
> 4042
>
> However, brick wall:
>
> timedelta.days = 100
> Traceback (most recent call last):
>   File "<string>", line 1, in <fragment>
> builtins.TypeError: can't set attributes of built-in/extension type
> 'datetime.timedelta'

timedlta objects are immutable. Once an object is created it's values
cannot be changed (much like a tuple). You need to create a new
timedelta object:

>>> from datetime import datetime, timedelta
>>> dt = datetime.now()
>>> print dt
2012-10-05 15:14:55.841000
>>> d = dt.date()
>>> print d
2012-10-05
>>> td = timedelta(days=7)
>>> print dt + td
2012-10-12 15:14:55.841000
>>> print d + td
2012-10-12

Oscar


More information about the Tutor mailing list