Sahat Yalkabov
Sahat Yalkabov

Reputation: 33624

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]

Upvotes: 2

Views: 4948

Answers (3)

Mark Ransom
Mark Ransom

Reputation: 308121

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.

Upvotes: 3

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

OR:

from datetime import datetime, timedelta

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

E.g:

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]

Upvotes: 4

Hamish
Hamish

Reputation: 23316

You could use datetime.datetime.strptime:

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

Upvotes: 2

Related Questions