[英]How to calculate day of the week provided the day and month
This program is strictly set in the year of 2014. However, I want to know if I am heading in the right direction. 该计划严格设置在2014年。但是,我想知道我是否朝着正确的方向前进。 This is what I have so far:
这是我到目前为止的内容:
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]
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
Which you can then pass into your day
list 然后可以将其传递到您的
day
列表中
If you can't use datetime
, this should work: 如果您不能使用
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 ----'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.