简体   繁体   中英

How to calculate day of the week provided the year and the day?

For example if I input the year - 2012 and the day 72, it should return Tuesday.The following code will return proper day of the week, but requires month as an input. How could I do this without the month argument, since I am not requiring a user to type in a month?

days = {0:'Monday', 1:'Tuesday', 2:'Wednesday', 3:'Thursday', 4:'Friday', 5:'Saturday', 6:'Sunday'}

userdate = date(year, month, day)
weekday = userdate.weekday()

return days[weekday]

OR:

from datetime import datetime, timedelta

startDate = datetime(your_year, 1, 1)
endDate = (startDate + timedelta(days=days_from_the_begining)).weekday()

Eg:

from datetime import datetime, timedelta

def get_weekday(year, dayOfTheYear):
    days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

    userWeekDay = (datetime(year, 1, 1) + timedelta(days=dayOfTheYear)).weekday()
    return days[userWeekDay]

Here's a version that can be adapted to any language. The divides need to be integer, I'm using // to make sure this works in Python 3.

def day_of_week(year, day, one_based=false):
    days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
    weekday = (year*365 + (year-1)//4 - (year-1)//100 + (year-1)//400 + day + (5 if one_based else 6)) % 7
    return days[weekday]

>>> day_of_week(2012, 72)
'Tuesday'

The odd part where it keeps dividing the year by different values accounts for the leap year rules. A year is a leap year when it is divisible by 4, except when it's divisible by 100 and not divisible by 400. Thus 2000 was a leap year but 1900 wasn't.

You could use datetime.datetime.strptime :

from datetime import datetime
weekday = datetime.strptime('%d %d' % (year, day_of_year), '%Y %j').weekday()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM