Home > Mobile >  Calculate the number of definite months in a period
Calculate the number of definite months in a period

Time:01-13

The start year, start month, end year, and end month are the inputs (like May'2022 to June'2024). If I need to calculate how many definite months are included in this period (like how many January, March, or December are in this period), how can I achieve this using Python?

CodePudding user response:

Use date_range with DatetimeIndex.month_name and Index.value_counts:

s = pd.date_range('2022-05-01','2024-06-01', freq='MS').month_name().value_counts()
print (s)
June         3
May          3
April        2
March        2
July         2
December     2
November     2
October      2
February     2
January      2
September    2
August       2
dtype: int64

Last select by index in Series called s:

print (s['January'])
2

print (s['March'])
2

CodePudding user response:

pandas date_range is a good helper here

import pandas as pd
ym = pd.date_range('2022-05-01','2024-06-01', freq='MS').strftime("%Y-%b").to_list()

print(ym)
def count_month(ym_list, month):
    return(sum(month in s for s in ym_list))

print(count_month(ym, "May"))
print(count_month(ym, "Jan"))

and the output is

['2022-May', '2022-Jun', '2022-Jul', '2022-Aug', '2022-Sep', '2022-Oct', '2022-Nov', '2022-Dec', '2023-Jan', '2023-Feb', '2023-Mar', '2023-Apr', '2023-May', '2023-Jun', '2023-Jul', '2023-Aug', '2023-Sep', '2023-Oct', '2023-Nov', '2023-Dec', '2024-Jan', '2024-Feb', '2024-Mar', '2024-Apr', '2024-May', '2024-Jun']
3
2
  •  Tags:  
  • Related