Last active
June 21, 2016 17:46
-
-
Save michaelhjulskov/0a0d7334081962c4195c to your computer and use it in GitHub Desktop.
date Business days functions - can be used in ecommerse for estimating delivery day
This file contains 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
def get_holidays(year=date.year): | |
easter_sunday = easter.easter(year) | |
holidays = [ | |
# These holidays have a fixed date | |
date(year,1,1), # New Year | |
date(year,5,1), # Labor Day | |
date(year,6,5), # Constitution Day (Grundlovsdag) | |
date(year,12,24), # Christmas Night | |
date(year,12,25), # 1st Christmas Day | |
date(year,12,26),# 2st Christmas Day | |
date(year, 12, 31), # 31. dec Nytårsaften | |
# These days have a date depending on easter | |
easter_sunday - timedelta(days=7), # Palmesøndag | |
easter_sunday - timedelta(days=3), # Skærtorsdag | |
easter_sunday - timedelta(days=2), # Langfredag | |
easter_sunday, # Easter Sunday | |
easter_sunday + timedelta(days=1), # Easter Monday (2. Påskedag) | |
easter_sunday + timedelta(days=26), # Great praior day (St. Bededag) | |
easter_sunday + timedelta(days=39), # Kristi Himmelfart | |
easter_sunday + timedelta(days=49), # Pentecost Sunday Pinsedag (7th Sunday after Easter) | |
easter_sunday + timedelta(days=50), # 1. Pinsedag | |
] | |
return holidays | |
def is_date_a_business_day(current_date=date.today()): | |
weekday = current_date.weekday() | |
if weekday > 4: # saturday=5, sunday = 6 | |
return False | |
holidays = get_holidays(current_date.year) | |
if current_date in holidays: | |
return False | |
return True | |
def date_by_adding_business_days(start_date=date.today(), add_days=1): | |
current_date = start_date | |
business_days_to_add = add_days | |
while business_days_to_add > 0: | |
current_date += timedelta(days=1) | |
if not is_date_a_business_day(current_date): | |
continue | |
business_days_to_add -= 1 | |
return current_date | |
def date_by_substracting_business_days(start_date=date.today(), add_days=1): | |
current_date = start_date | |
business_days_to_add = add_days | |
while business_days_to_add > 0: | |
current_date -= timedelta(days=1) | |
if not is_date_a_business_day(current_date): | |
continue | |
business_days_to_add -= 1 | |
return current_date | |
def get_next_business_day(current_date=date.today()): | |
return date_by_adding_business_days(current_date, 1) | |
def get_previous_business_day(current_date=date.today()): | |
return date_by_substracting_business_days(current_date, 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment