Count days from beginning of year/month to today

Viewed 293

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.

2 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 

This is less simple than the other answer, but it also works.

from time import mktime, strptime
from datetime import datetime, timedelta

date = '2020-05-05'
time_format = '%Y-%m-%d'

def string_to_date(string, time_format):
    string = string.split(' ')[0]
    struct = strptime(string, time_format)
    obj = datetime.fromtimestamp(mktime(struct))
    return obj

def get_start_of_month(date):
    month_day = date.day
    to_remove = timedelta(days=month_day-1)
    new_date = date - to_remove
    return new_date

def get_start_of_year(date):
    new_date = datetime(date.year, 1, 1)
    return new_date

def time_from_month(date):
    start = get_start_of_month(date)
    obj = date - start
    return obj.days

def time_from_year(date):
    start = get_start_of_year(date)
    obj = date - start
    return obj.days

print(time_from_month(obj))
print(time_from_year(obj))
Related