Last active
October 20, 2019 23:16
-
-
Save sonnyksimon/5fde844d1f5c0bfc40969a363f287e81 to your computer and use it in GitHub Desktop.
split_years_to_months.py
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 datetime | |
| import calendar | |
| import re | |
| def last_day_of_month(date): | |
| return date.replace(day=31) if date.month == 12 else date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1) | |
| def format_date(date): | |
| return date.strftime("%Y-%m-%dT%H:%M:%S.%fZ") | |
| def get_interval(start, end): | |
| return dict(start=format_date(start), end=format_date(end)) | |
| def split_years_to_months(start, end, number_of_years): | |
| days = 0 | |
| number_of_months = 12 * number_of_years | |
| intervals = [] | |
| #intervals.append(get_interval(start, end)) | |
| intervals.append(get_interval(start,last_day_of_month(start))) | |
| for i in range(number_of_months-1): | |
| factored_months = (start.month+i) %12 | |
| factored_months = 12 if factored_months == 0 else factored_months | |
| factored_year = start.year + (start.month+i // 12) | |
| days += calendar.monthrange(factored_year, factored_months)[1] | |
| next_start = start + datetime.timedelta(days=days) | |
| next_end = last_day_of_month(next_start) | |
| intervals.append(get_interval(next_start, next_end)) | |
| return intervals | |
| def parse_amount_from_period(period_string): | |
| """ | |
| Gets the amount from the period string. | |
| >>> parse_amount_from_period('P10M') | |
| 10 | |
| """ | |
| return int(re.findall(r'\d+', period_string)[0]) | |
| if __name__ == '__main__': | |
| start = datetime.datetime(2019,1,1) | |
| end = datetime.datetime(2020,12,31) | |
| number_of_years = parse_amount_from_period("P2Y") | |
| intervals = split_years_to_months(start, end, number_of_years) | |
| print(intervals) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment