Skip to content
Snippets Groups Projects
utils.py 927 B
Newer Older
import re
from pathlib import Path
from typing import Literal
from pandas import to_datetime, DataFrame, Timestamp
from pandas.tseries.offsets import DateOffset

def extract_run_date_from_filename(
        path: str | Path,
        pattern: str = r'[\d]{4}-[\d]{2}-[\d]{2}'
        ) -> Timestamp:
    if isinstance(path,Path):
        path = str(path.absolute())
    run_date = to_datetime(re.search(pattern,path).group(),format='%Y-%m-%d')
    return run_date

def as_timedelta(
        val: int,
        unit: Literal['D','W','M','Y']
        ) -> DateOffset:
    if unit == 'D':  # Days
        return DateOffset(days=val)
    elif unit == 'W':  # Weeks
        return DateOffset(weeks=val)
    elif unit == 'M':  # Months
        return DateOffset(months=val)
    elif unit == 'Y':  # Years
        return DateOffset(years=val)
    else:
        raise ValueError(f"{unit} is not a valid unit. Choose one of D, W, M, or Y")