Last active
August 29, 2015 14:18
-
-
Save pl77/89d619dfbbb758b8a061 to your computer and use it in GitHub Desktop.
Calculate North American Week Number having Sunday as Day 1 and January 1 as Week 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import calendar | |
| import datetime | |
| def usaweeknum(year, month, day): | |
| """North American week number for weeks beginning on a Sunday | |
| Week 1 is week containing January 1 | |
| Week 1 contains any days from the end of the previous year | |
| For example, years 2011 and 2016 contain 53 weeks | |
| Matches output from sites like calendar-365.com or timeanddate.com | |
| Similar to "Type 2: every week has seven days, # Week 1 contains January 1" found at | |
| http://www.merlyn.demon.co.uk/weekcalc.htm#T2 | |
| Applies to countries found under "Sunday is the first day of week" on this list: | |
| http://www.pjh2.de/datetime/weeknumber/wnd.php?l=en | |
| Code adapted from github.com/django/django/blob/master/django/utils/dateformat.py""" | |
| year_days = [None, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] | |
| day_of_year = year_days[month] + day | |
| # pull from isoweekday, push all days +1 and flip Sunday from end to beginning | |
| day_of_week = int(datetime.datetime(year, month, day).isoweekday())+1 | |
| if day_of_week == 8: | |
| day_of_week = 1 | |
| yearlastday = int(datetime.datetime(year, 12, 31).isoweekday())+1 # same for last day of year | |
| if yearlastday == 8: | |
| yearlastday = 1 | |
| day1nextyear = int(datetime.datetime(year + 1, 1, 1).isoweekday())+1 # first day of next year | |
| if day1nextyear == 8: | |
| day1nextyear = 1 | |
| if calendar.isleap(year) and month > 2: # add extra day for leap years | |
| day_of_year += 1 | |
| if yearlastday == 7: # if the last day is a Saturday all dates fall within calendar year | |
| week_number = int(datetime.datetime(year, month, day).strftime("%U"))+1 | |
| else: | |
| if calendar.isleap(year): | |
| i = 366 | |
| else: | |
| i = 365 | |
| if (i - day_of_year) < (7 - (8 - day1nextyear)): # add last days of year to next year | |
| week_number = 1 | |
| else: | |
| j = day_of_year + (7 - day_of_week) + (day1nextyear - 1) | |
| week_number = j // 7 | |
| print("usaweeknum ({yr}, {mo}, {dy}) = ".format(yr=year, mo=month, dy=day), week_number) | |
| return week_number | |
| for y in range(2010, 2019): | |
| print("---------{}-----------".format(y)) | |
| for d in range(1, 32): | |
| if d < 18: | |
| usaweeknum(y, 1, d) | |
| elif d > 15: | |
| usaweeknum(y, 12, d) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment