我正在尝试在 python 3 中制作一个简单的代码,它会在您输入年月日时显示日期。这是代码:
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")
上面的代码有效,但我尝试这样做
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")
所以我可以让用户输入他们自己的一天,但它给我以下错误:
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,'
如果有帮助,我使用了输入 2016、4、29。
请您参考如下方法:
你可以这样做:
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() 需要 3 个整数,但 input() 返回一个字符串。这意味着我们必须:
- 将
input()返回的字符串用逗号分割成三部分 - 将每个部分转换为整数
- 将这些部分提供给
datetime.date()
如果你问我,这更有意义:
from datetime import datetime
d = datetime.strptime(input(), '%Y,%m,%d').weekday()
print(d)
datetime.strptime() 将字符串作为输入,这很方便,因为 input() 恰好返回一个字符串。这意味着不需要拆分和转换/转换。您可以在 datetime docs 中找到 strptime() 支持的所有不同日期格式.
