Created
July 6, 2018 04:11
-
-
Save EdMan1022/9bc1ea71ea1460c173f7c43f2d540839 to your computer and use it in GitHub Desktop.
Creates an interval of monthly dates, but replacing weekend dates with the nearest weekday date
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
import datetime | |
from dateutil import rrule as rr, relativedelta as rd | |
start_date = datetime.datetime(year=2017, month=1, day=1) | |
end_date = datetime.datetime(year=2018, month=1, day=1) | |
# Generate rule for valid dates under simple rule (Monthly from start until end) | |
valid_rule = rr.rrule(freq=rr.MONTHLY, dtstart=start_date, until=end_date) | |
# Generate rule for dates that would be invalid (weekend days) | |
invalid_rule = rr.rrule(freq=rr.DAILY, dtstart=start_date, until=end_date, | |
byweekday=[rr.SA, rr.SU]) | |
# Convert rules into sets to allow flexible comparisons | |
valid_dates = set(valid_rule) | |
invalid_dates = set(invalid_rule) | |
# Get the members of the valid dates not in the invalid dates (good dates) | |
valid_chosen = valid_dates.difference(invalid_dates) | |
# Get the members of the valid dates in the invalid dates (bad dates) | |
invalid_chosen = valid_dates.intersection(invalid_dates) | |
# For each invalid date, find the closest Monday, | |
# and append that to the list instead | |
for date in invalid_chosen: | |
new_date = date + rd.relativedelta(weekday=rr.MO) | |
valid_chosen.add(new_date) | |
for i in sorted(valid_chosen): | |
print(i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment