2014-02-16 37 views
1

該程序嚴格設置在2014年。但是,我想知道我是否正朝着正確的方向前進。這是我到目前爲止有:如何計算一週中的某一天提供的日期和月份

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.""" 

    day = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'] 
    weekday = (d + (2.6*m - 0.2) -2*20 + 2014 + (2014//4) + (20//4)) 
    return day[weekday] 
+0

'DateTime'立即爲您解決這個問題。只需檢查文檔。如果你在日期中給出構造;你可以使用格式化程序來輸出'day'。不要重新發明輪子;) – 2014-02-16 22:20:16

回答

1

如果你不能使用datetime,這應該工作:

def day(d, m): 
    day = (sum((31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)[:m-1]) + d + 3) % 7 
#   ^             ^ ^^^^
#   '---- adding up the days in the months    |  | | | | 
#     up to but not including the current month ----'  | | | | 
#         plus the current day of the month ----' | | | 
#         and the day of the week on 12/31/2013 ----' | | 
#     modulus (%) is what's left over after integer division ----' | 
#              seven days in a week ----' 
7

Don't reinvent the wheel

>>> import datetime 
>>> datetime.datetime(2014, 2, 16).strftime('%a') 
'Sun' 

Or as a number

>>> import datetime 
>>> datetime.datetime(2014, 2, 16).weekday() 
6 

然後你就可以進入你的day列表

+1

添加導入子句:)爲信息的緣故 – markcial

+0

啊我已經考慮使用導入日期時間,但是,我還沒有涉及該部分。還有另一種方法可以做到嗎? – Yozuru

+0

清理工'從日期時間導入日期時間'。甚至給它一個新的(更短)的名字:) – 2014-02-16 22:31:30

相關問題