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

akleider at sonic.net akleider at sonic.net
Sun Oct 7 04:29:12 CEST 2012


> On 10/06/2012 07:19 PM, Richard D. Moores wrote:
>> On Fri, Oct 5, 2012 at 7:15 AM, Walter Prins <wprins at gmail.com> wrote:
>>
>>> Does this hint help?
>>>
>>>>>> import datetime
>>>>>> mydate = datetime.date(2012,10,5)
>>>>>> mydate = mydate + datetime.timedelta(days=30)
>>>>>> print mydate
>>> 2012-11-04
>> Yes! Thanks to all for their rapid responses.
>>
>> But now I'm thinking it would be handy to not only know that, say, 500
>> days from today is 2014-02-18, but to know what day if the week that
>> is. I suppose the calendar module is to be used for this, but I
>> haven't been able to get it to work for me. So what day of the week IS
>> 2014-02-18?
>>
>> The docs say
>> calendar.weekday(year, month, day)
>> Returns the day of the week (0 is Monday) for year (1970–...), month
>> (1–12), day (1–31).
>>
>>>>> import calendar
>>>>> calendar.weekday(2014, 2, 18)
>> 1
>>
>> That "1" means Tuesday, right? But how can I use calendar to print out
>> that word, "TUESDAY"?
>>
>> Thanks
>>
>
> To turn an integer (0-6, or whatever) into a string, just use a tuple of
> the same size:
>
> tran = ("MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY",
> "SATURDAY", "SUNDAY")
> i = 1
> print tran[i]
>
> (prints "TUESDAY")
>
> Note that I'm not sure of the actual mapping of the integers coming out
> of the weekday function, so you might have to rearrange the strings above.

I'm also not sure but I seem to remember that it is
("SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY",
"SATURDAY", "SUNDAY")
which I think is extremely clever because it gets around the problem
created by the fact that some people (misguided in my view) begin the week
with Sunday instead of ending with it.




More information about the Tutor mailing list