2014-02-16 26 views
0

我在程序方面遇到了麻煩。所以我想寫一個函數返回一天的名字。 (例如:2014年1月1日是星期三)我只嚴格處理2014年度。我將會有的輸入是d =日,m =月。Python - 寫一個返回一個日期名稱的函數

這是我到目前爲止。

def day(d,m): # Function for determining day name for a given date. 
    """Where m is an integer from 1 through 12 expressing a month, and d is an integer from 
    1 through 31 expressing the day-part of a date in 2014.""" 

    if 1<=m<=12: 
     return 

    elif 1<=d<=31: 
     return ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'] 

    else: 
     return "Error" 
+0

如果你想要一個公式,請開始[這裏](http://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week)。 [Doomsday method](http://en.wikipedia.org/wiki/Doomsday_rule)並不難實現。 – dawg

回答

2

使用datetime module

import datetime as DT 
def day(d,m): # Function for determining day name for a given date. 
    """Where m is an integer from 1 through 12 expressing a month, and d is an 
    integer from 1 through 31 expressing the day-part of a date in 2014.""" 

    date = DT.date(2014, m, d) # 1 
    return date.strftime('%A') 

這將引發ValueError如果2014/m/d是不是一個有效日期。通常情況下,拋出異常比返回字符串如"Error"更可取。

+0

我正在考慮使用它。然而,我想看看是否有可能只用if,elif和else語句來完成。 – Yozuru

相關問題