Quarters Calculator

Find the fiscal or calendar quarter for any date, with start/end dates and days elapsed.

Часто задаваемые вопросы

Реализация кода

from datetime import date, timedelta
import calendar

def calendar_quarter(d):
    """Return Q1-Q4 for a calendar year date"""
    return (d.month - 1) // 3 + 1

def fiscal_quarter(d, fiscal_start_month=1):
    """Return fiscal quarter given fiscal year start month"""
    offset = (d.month - fiscal_start_month) % 12
    return offset // 3 + 1

def quarter_dates(year, q, fiscal_start_month=1):
    """Return (start, end) dates for a given fiscal quarter"""
    start_month = ((fiscal_start_month - 1 + (q - 1) * 3) % 12) + 1
    start_year = year if start_month >= fiscal_start_month else year - 1
    start = date(start_year, start_month, 1)
    # End = last day of 3rd month
    end_month = (start_month - 1 + 3 - 1) % 12 + 1
    end_year = start_year if end_month >= start_month else start_year + 1
    end = date(end_year, end_month, calendar.monthrange(end_year, end_month)[1])
    return start, end

d = date.today()
q = calendar_quarter(d)
start, end = quarter_dates(d.year, q)
print(f"Q{q}: {start} to {end}")
print(f"Days elapsed: {(d - start).days + 1}")
print(f"Days remaining: {(end - d).days}")

# Fiscal year starting April (UK standard)
fq = fiscal_quarter(d, fiscal_start_month=4)
print(f"UK Fiscal Q{fq}")

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.