python - 使用 python 日期输入

标签 python python-3.x

我正在尝试用 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() 支持的所有不同日期格式。 .

关于python - 使用 python 日期输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36946056/

相关文章:

python - BeautifulSoup 不拾取单个标签

Python/Django : log to console under runserver, 在 Apache 下登录到文件

Python过滤函数——单一结果

Python 单元测试数据提供程序

python - Bottle 是否有基于类的 View

python - 使用类似形状的函数获取一维 numpy.array 的 "1"

python - 如何将值传递给Python中正在运行的进程

python - 使用 Python winreg 更改注册表项未生效,但不会抛出错误

python - Alexa Lambda 函数获取用户的全名

python-3.x - 属性错误 : module 'tensorflow' has no attribute 'Graph'