Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count days from beginning of year/month to today

Say we have a dataframe (df):

opendate
2020-08-04
2018-06-24
2011-03-17
2019-11-20

I want to do two things:

  1. For each date, count the number of days from beginning of the particular year to the date
  2. For each date, count the number of days from beginning of the particular month to the date

In R, I can do this by the following code:

Year_Month_Diff <- function(x, start) as.numeric(x - as.Date(cut(start, "year")));
df = transform(df, Year_day_played = Year_Month_Diff(opendate, opendate));

Month_Diff <- function(x, start) as.numeric(x - as.Date(cut(start, "month")));
df= transform(df, Month_day_played = Month_Diff(opendate, opendate));

Any help for the python equivalent will be appreciated.

like image 508
Michael Okelola Avatar asked Dec 06 '25 04:12

Michael Okelola


1 Answers

The month is really simple, just call .dt.day.

For the year case, you subtract the date from Jan 1 of the same year, and count the number of days.

Assuming opendate is already of type Timestamp:

df['Days since BOM'] = df['opendate'].dt.day
df['Days since BOY'] = (df['opendate'] - (df['opendate'] - pd.tseries.offsets.YearBegin())).dt.days

Thanks to @ChrisA, there's an even simpler solution for the year case:

df['Days since BOY'] = df['opendate'].dt.dayofyear 
like image 64
Code Different Avatar answered Dec 07 '25 20:12

Code Different