Last active
February 13, 2023 20:32
-
-
Save xescuder/0aeec5cbf43cf3d0ee46c5f086a1a8f2 to your computer and use it in GitHub Desktop.
Python date utils for building ranges and periods
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
from datetime import date, datetime, timedelta | |
from dateutil.relativedelta import relativedelta | |
def build_formatted_range(interval: str, range_start: date | datetime = None, range_end: date | datetime = None, | |
period: str = None): | |
new_start = range_start | |
new_end = range_end | |
if range_end is None: | |
new_end = date.today() | |
if range_start is None: | |
new_start = backdate(date=new_end, period=period) | |
if new_start is not None and (isinstance(new_start, date) or isinstance(new_start, datetime)): | |
new_start = convert_date_to_str(new_start, interval) | |
if new_end is not None and (isinstance(new_end, date) or isinstance(new_end, datetime)): | |
new_end = convert_date_to_str(new_end, interval) | |
return new_start, new_end | |
def backdate(to_date: date | datetime, period: str): | |
new_date = to_date | |
periods = int(''.join([s for s in period if s.isdigit()])) | |
if periods > 0: | |
if 'm' in period: | |
new_date = new_date - timedelta(minutes=periods) | |
elif 'h' in period: | |
new_date = new_date - timedelta(hours=periods) | |
elif 'w' in period: | |
new_date = new_date - timedelta(weeks=periods) | |
elif 'M' in period: | |
new_date = new_date - relativedelta(months=periods) | |
elif 'y' in period: | |
new_date = new_date - relativedelta(years=periods) | |
else: # days | |
new_date = new_date - timedelta(days=periods) | |
return new_date | |
FORMAT_RANGE_DICT = {'d': '%Y-%m-%d', 'h': '%Y-%m-%d %H:%M:%S'} | |
def convert_date_to_str(range_date: date | datetime, interval='1d'): | |
return range_date.strftime(FORMAT_RANGE_DICT.get(interval[-1])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment