Dnaiel Dnaiel - 1 year ago 97
Python Question

transform month to discrete time periods

Let us say I have a list of dates in datetime.date format. I want to transform date in months into discrete (integer) periods.


myList = [datetime.date(2015,02,08), datetime.date(2015,02,25), datetime.date(2015,05,03), datetime.date(2016,03,27)]

Since the smallest year/month is 2015/02 then that month is equivalent to 0. The next month 2015/03 would be 1, etc. Until last month 2016/03 would be 13.

I'd want a function for which I give it the start date, and then it gives me the discrete month.


discretizeMo(start_date, date_of_interest)
discretizeMo('2012-02-01', '2013-01-01')

would return 11, etc.

Answer Source

Well, since you drop the days, the usual date arithmetic is of no use here. The simplest solution would be to convert years & months to a scale:

def discretizeMo(d1, d2):
    return (d2.year * 12 + d2.month) - (d1.year * 12 + d1.month)

The result is the number of months passed since the d1 date till the d2 date.

That simple.

If you want to split it into smaller units of fixed length (e.g., weeks), it will be different:

def discretizeMo(d1, d2):
    return (d2 - d1).days // 7

The difference comes from the variable duration of months in days: 28-29-30-31.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download