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

Richard D. Moores rdmoores at gmail.com
Fri Oct 5 15:47:42 CEST 2012


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'

Advice, please.

Dick Moores


More information about the Tutor mailing list