How Year, Month in "def get_customers(yearmonth)" works

def get_customers(yearmonth):
    year = yearmonth//100
    month = yearmonth-year*100
    date = dt.datetime(year, month, 1)

I really need to understand the working of year and month variables in this function …

Refer this - https://app.dataquest.io/m/468/business-metrics/8/churn-rate

2 Likes

Hi @4jvarun

Basically the function takes an input yearmonth, in this case that’s a column in churn. That column has values like this 201101

So what it does is:

  1. Takes yearmonth and makes a floor division by 100 so you get only the year. IE: 201101 // 100 = 2011
  2. Takes yearmonth and substract year (that you found in the step before) and multiplies it by 100 IE: 201101 - 2011 * 100 = 201101 - 201100 = 1
  3. Then you use dt.datetime(year, month, 1) to transform it into a date

Basically year and month are temporal variables that you create to “save” chunks of data that you might need later

So the function would be something like this:

def get_customers(201101):
  year = 201101 // 100
  year = 2011
  month = 201101 - 2011 * 100
  month = 1
  date = dt.datetime(year, month, 1)
  date = dt.datetime(2011, 1, 1)

Hope i made myself clear and that you understood the working of year and month

Good luck!

6 Likes

Thanks, that was of great help

Hi @4jvarun,

Was confusing for me too, but I went with very easy basic approach for this.

def get_customers(yearmonth):
    yearmonth = str(yearmonth) 
    year = int(yearmonth[:4])
    month = int(yearmonth[4:])
    first_date = dt.datetime(year,month,1)
    
    return ( (subs['start_date']<first_date)&(first_date <= subs['end_date']) ).sum()
1 Like

Hi! inside get_customers(), do i have to put yearmonth? or i can use anyword like xxxxxx to represent 201101?

Hi!
No, when you are defining the function you can use whatever name you want, it’s like the helper in the for loop, just a temporal name that will be replaced when you call the function. So obviously the recomendation is that you use a word that helps to describe what you need as the argument. That’s why in this case yearmonth is used, but date would have been another option