Reputation: 57
I am trying to make a simple code in python 3 that shows you the day when you enter the month year and day. This is the code:
from datetime import date
s = date(2016, 4, 29).weekday()
if s == 0:
print ("mon")
if s == 1:
print ("tue")
if s == 2:
print ("wed")
if s == 3:
print ("thurs")
if s == 4:
print ("fri")
if s == 5:
print ("sat")
if s == 6:
print ("sun")
The above code works, but I tried to do
from datetime import date
s = date(int(input())).weekday()
if s == 0:
print ("mon")
if s == 1:
print ("tue")
if s == 2:
print ("wed")
if s == 3:
print ("thurs")
if s == 4:
print ("fri")
if s == 5:
print ("sat")
if s == 6:
print ("sun")
so I could let users enter their own day, but it gives me the following error:
Traceback (most recent call last):
File "..\Playground\", line 2, in <module>
s = date(int(input())).weekday()
ValueError: invalid literal for int() with base 10: '2016,'
I used the input 2016, 4, 29 if it helps.
Upvotes: 2
Views: 354
Reputation: 4010
You could do:
from datetime import date
usr_date = [int(x) for x in input().split(",")]
d = date(usr_date[0], usr_date[1], usr_date[2]).weekday()
print (d)
datetime.date()
expects 3 integers but input()
returns a string. This means that we have to:
input()
by comma to get three partsdatetime.date()
This makes more sense, if you ask me:
from datetime import datetime
d = datetime.strptime(input(), '%Y,%m,%d').weekday()
print(d)
datetime.strptime()
takes a string as input which is convenient because input()
happens to return a string. This means that the splitting and casting/converting isn't necessary. You can find all the different date formats supported by strptime()
in the datetime docs.
Upvotes: 2