Skip to content

Instantly share code, notes, and snippets.

@jplsightm
Last active June 5, 2018 14:30
Show Gist options
  • Save jplsightm/383a163bec806d5dca3de09dca069861 to your computer and use it in GitHub Desktop.
Save jplsightm/383a163bec806d5dca3de09dca069861 to your computer and use it in GitHub Desktop.
Early Attempt at identifying fiscal week
from datetime import datetime, timedelta
import pandas as pd
def get_fw(date, fiscal_start=datetime(1970, 1,1), calendar_day=False):
"""
Obtain fiscal week from a datetime object.
:fiscal_start: Indicate the start of a fiscal year
:calendar_day: If False the first full week is Week 1.
"""
if datetime(1970, date.month, date.day) > datetime(1970, fiscal_start.month, fiscal_start.day):
offset = 1 if fiscal_start.isocalendar()[2] == 1 or calendar_day else 0
week = date.isocalendar()[1] - fiscal_start.isocalendar()[1] + offset
else:
weeks_in_year = 53 if datetime(date.year, fiscal_start.month, fiscal_start.day).isocalendar()[2] > datetime(date.year - 1, fiscal_start.month, fiscal_start.day).isocalendar()[2] else 52
offset = 0 if fiscal_start.isocalendar()[2] == 1 or calendar_day else 1
week = weeks_in_year + (date.isocalendar()[1] - fiscal_start.isocalendar()[1]) + offset
return (week, date.year - 1 if week == 53 else date.year)
def get_fw_string(*args, **kwargs):
"""
A wrapper for get_fw. This provides the date in a human readable format.
"""
date_tuple = get_fw(*args, **kwargs)
return '{1} - Week {0}'.format(date_tuple[0], date_tuple[1])
def get_month(date):
return (date.month, date.year)
def get_month_string(*args, **kwargs):
month_tuple = get_month(*args, **kwargs)
return '{} - {}'.format(month_tuple[1], month_tuple[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment