2016-04-29 84 views
2

我想在python 3中做一個簡單的代碼,顯示你輸入月份和日期的那一天。這是代碼:使用輸入的日期python

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。

+2

的可能的複製[ValueError異常:無效字面對於int()與底座10: ''](http://stackoverflow.com/questions/1841565/valueerror-invalid-literal-for-int-with-base-10 ) – jgr208

+1

'2016,4,29'不是有效整數。 – fukanchik

回答

2

你可以這樣做:

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()支持的所有不同日期格式。