EN VI

How create a list with only the months that have complete days in Python?

2024-03-12 20:30:04
How create a list with only the months that have complete days in Python

Consider the following DateTimeIndex:

from calendar import monthrange
import pandas as pd

index_h = pd.date_range(start='2022-01-04 00:00:00', end='2023-01-10 23:00:00', freq='H')

We can see that both January/2022 and January/2023 are incomplete.

How can I create a list that contains the Month/Year that are complete in that range?

I have been trying to use monthrange from calendar to count the values, but not really sure how to proceed from here:

years_months = index_h.to_period('M').unique()
complete_month_year_list = []
for year_month in years_months:
    num_days = monthrange(year_month.year, year_month.month)[1]
    if what_goes_here??? == num_days:    
        print(f"Month {year_month.month} of year {year_month.year} is complete.")
        complete_month_year_list.append(?????)
    else:
        print(f"Month {year_month.month} of year {year_month.year} is not complete.")

Solution:

You can achieve it by checking if the number of days in the month is equal to the total number of hours in that month. If they are equal, it means that the month is completed.

By comparing the length of the index for that month with the expected number of hours in that month.

from calendar import monthrange
import pandas as pd

index_h = pd.date_range(start='2022-01-04 00:00:00', end='2023-01-10 23:00:00', freq='H')

years_months = index_h.to_period('M').unique()
complete_month_year_list = []

for year_month in years_months:
    # Calculate the number of days in the month
    num_days = monthrange(year_month.year, year_month.month)[1]
    # Filter the index for the current month and year
    month_index = index_h[index_h.to_period('M') == year_month]
    # Check if the number of hours in the month is equal to the number of days in the month
    if len(month_index) == num_days * 24:
        print(f"Month {year_month.month} of year {year_month.year} is complete.")
        complete_month_year_list.append(year_month)
    else:
        print(f"Month {year_month.month} of year {year_month.year} is not complete.")

print("List of complete months:", complete_month_year_list)
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login