On 02/06/2018 03:36 PM, Mark Lawrence wrote:
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

Thanks. I already got it up and running. Much appreciated.

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to