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

Mark Lawrence breamoreboy at yahoo.co.uk
Fri Oct 5 16:11:33 CEST 2012


On 05/10/2012 14:47, Richard D. Moores 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'
>
> Advice, please.
>
> Dick Moores
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

 From the docs http://docs.python.org/library/datetime.html class 
timedelta( [days[, seconds[, microseconds[, milliseconds[, minutes[, 
hours[, weeks]]]]]]])

hence timedelta(days=100)

-- 
Cheers.

Mark Lawrence.



More information about the Tutor mailing list