What fraction of the year has passed until a given Timestamp in pandas?
To compute what fraction of the year has passed since the start of the year, use this function:
import pandas as pd
def fraction_of_year_passed(date):
"""Compute what fraction of the current year has already passed up to the given date"""
start_of_year = pd.Timestamp(now.year, 1, 1)
start_of_next_year = pd.Timestamp(now.year + 1, 1, 1)
# Compute seconds in entire year and seconds since start of year
entire_year_seconds = (start_of_next_year - start_of_year).total_seconds()
seconds_since_start_of_year = (date - start_of_year).total_seconds()
return seconds_since_start_of_year / entire_year_seconds
Usage example:
print(fraction_of_year_passed(pd.Timestamp("2020-03-01"))) # prints 0.16393442622950818
Detailed explanation:
First, we define that start of the calendar year date
belongs to, and the start of the calendar year after that:
start_of_year = pd.Timestamp(now.year, 1, 1)
start_of_next_year = pd.Timestamp(now.year + 1, 1, 1)
Now we compute the number of seconds in the entire year and the number of seconds passed between the start of the year and date
:
entire_year_seconds = (start_of_next_year - start_of_year).total_seconds()
seconds_since_start_of_year = (date - start_of_year).total_seconds()
The rest is simple: Just divide seconds_since_start_of_year / entire_year_seconds
to obtain what fraction of the year has passed until date
.