date - First month of quarter given month in Python -


given month in numeric form (e.g., 2 february), how find first month of respective quarter (e.g., 1 january)?

i read through datetime module documentation , pandas documentation of datetime functions, ought relevant, not find function solves problem.

essentially, trying understand how produce function 1 below that, given month x, outputs number corresponding first month of x's quarter.

>> first_month_quarter(5) 4 

it's simple mapping function needs convert:

1 2 3 4 5 6 7 8 9 10 11 12            |            v 1 1 1 4 4 4 7 7 7 10 10 10 

this can done in number of ways integral calculations, 2 of are:

def firstmonthinquarter(month):     return (month - 1) // 3 * 3 + 1 

and:

def firstmonthinquarter(month):     return month - (month - 1) % 3 

the first involves integer division of month converted zero-based month zero-based quarter, multiplication turn zero-based month (but month @ start of quarter), adding 1 again make range 1..12.

month  -1  //3  *3  +1 -----  --  ---  --  --     1   0    0   0   1     2   1    0   0   1     3   2    0   0   1     4   3    1   3   4     5   4    1   3   4     6   5    1   3   4     7   6    2   6   7     8   7    2   6   7     9   8    2   6   7    10   9    3   9  10    11  10    3   9  10    12  11    3   9  10 

the second subtracts position within quarter (0, 1, 2) month starting month.

month(a)  -1  %3(b)  a-b --------  --  -----  ---        1   0      0    1        2   1      1    1        3   2      2    1        4   3      0    4        5   4      1    4        6   5      2    4        7   6      0    7        8   7      1    7        9   8      2    7       10   9      0   10       11  10      1   10       12  11      2   10 

Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -