[Tutor] What is day of week from either 20180211 or 02112018
Mark Lawrence
breamoreboy at gmail.com
Tue Feb 6 15:36:48 EST 2018
On 06/02/18 19:45, Ken Green wrote:
> Greeting: I have been trying to determine the day of
> the week when inputting year + month + date. I have
> not yet been able to determine what is really needed
> for datetime and later on the date in the program below.
> Running Python 2.7 on Ubuntu 16.04. Thanks.
> ===========================================
> # A_Weekday.py
> from datetime import date
> year = "2018"
> monthdate = raw_input ("Enter the month and date (MDD or MMDD): ")
> print
> if (len(monthdate)) == 3:
> month = monthdate[0:1]
> month = "0" + month
> day = monthdate[1:3]
> else:
> month = monthdate[0:2]
> day = monthdate[2:4]
> print month, day, year; print
> print year, month, day; print
> datecode = year + month + day
> print datecode
> print
> answer = datetime.date(year, month, day).weekday()
> print answer
> ==================================================
> Error message below:
> Enter the month and date (MDD or MMDD): 211
> 02 11 2018
> 2018 02 11
> 20180211
> Traceback (most recent call last):
> File "A_Weekday.py", line 20, in <module>
> answer = datetime.date(year, month, day).weekday()
> NameError: name 'datetime' is not defined
>
There's no need for the `datetime` as you've imported `date` directly
into the namespace. Correct that problem and you'll still fail as
you're passing strings instead of integers. I'd just force your
`monthdate` to be MMDD and pass that into `strptime` with `year`.
>>> year = '2018'
>>> monthdate = '0211' # skipping the input code.
>>> from datetime import datetime
>>> datetime.strptime(year + monthdate, '%Y%m%d')
datetime.datetime(2018, 2, 11, 0, 0)
>>> datetime.strptime(year + monthdate, '%Y%m%d').weekday()
6
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Tutor
mailing list