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

Albert-Jan Roskam fomcl at yahoo.com
Fri Oct 5 16:23:01 CEST 2012



----- Original Message -----

> From: Richard D. Moores <rdmoores at gmail.com>
> To: Tutor List <tutor at python.org>
> Cc: 
> Sent: Friday, October 5, 2012 3:47 PM
> Subject: [Tutor] Through a glass, darkly: the datetime module
> 
> 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.

Hello,

Using Python 2.6:
import datetime
ndays = 10
print (datetime.datetime.today() + datetime.timedelta(days=ndays)).strftime("%Y-%m-%d") # prints  '2012-10-15'

Regards,


More information about the Tutor mailing list