days_in_month#
Overview#
NCL’s days_in_month calculates the number of days in a month given a month and year.
Grab and Go#
import cftime
day = 1
month = 2
year = 2024
days = cftime.datetime(year, month, day, calendar='standard').daysinmonth
days
29
Using the calendar module#
The calendar module is part of the Python Standard Library and could be sufficient to calculate the number of days in a month.
from calendar import monthrange
month = 2
year = 1500
first_day, num_days = monthrange(year, month)
print(f"Month {month} in {year} has {num_days} days")
Month 2 in 1500 has 28 days
However, the calendar only uses a proleptic Gregorian calendar. If you need to work with other calendars, the calendar module will not be sufficient.
Using cftime#
cftime supports all of the CF Convention calendars. Here’s how you can use cftime to calculate the number of days in a month.
import cftime
day = 1
month = 2
year = 1500
days = cftime.datetime(year, month, day, calendar='standard').daysinmonth
print(f"standard calendar: \t\t\t\t month {month} in {year} has {days} days")
days = cftime.datetime(year, month, day, calendar='proleptic_gregorian').daysinmonth
print(f"proleptic Gregorian calendar: \t month {month} in {year} has {days} days")
days = cftime.datetime(year, month, day, calendar='julian').daysinmonth
print(f"Julian calendar: \t\t\t\t month {month} in {year} has {days} days")
days = cftime.datetime(year, month, day, calendar='360_day').daysinmonth
print(f"360 day calendar: \t\t\t\t month {month} in {year} has {days} days")
standard calendar: month 2 in 1500 has 29 days
proleptic Gregorian calendar: month 2 in 1500 has 28 days
Julian calendar: month 2 in 1500 has 29 days
360 day calendar: month 2 in 1500 has 30 days
Differences between cftime and NCL’s days_in_month#
Calendars#
The calendars available in cftime and NCL’s days_in_month, while both based on the CF Conventions calendars, are slightly different.
cftimedoes support using"none"as a calendar type, but not for this particular function.NCL’s
days_in_monthdoes not support theproleptic_gregoriancalendar.
Numerical Differences#
Additionally, the "standard" and "gregorian" calendars seem to disagree for some historical dates.
Input type#
Notably, using cftime to calculate the number of days in a month works by getting a daysinmonth value from a cftime.datetime object, which means that the calculations for days in a month have to be collected through each date individually, while NCL’s days_in_month can take in multidimensional integer arrays, given that the year and month arrays have the same dimensions.
Python Resources#
The
calendarmodule documentation.“Time series data” for working with time series data in xarray