DJV
DJV

Reputation: 873

Python Timedelta Arithmetic With noleap Calendars

I'm working with CMIP5 data that has time units of "days since 1-1-1850". To find the current day I'm working with in the file, I would normally just do a timedelta addition from 1-1-1850 and the time value (in days) for the datapoint that I'm working with. However, CMIP5 (or at least the file I'm using) uses a 'noleap' calendar, meaning that all years are only 365 days.

In my current case, when dealing with the datapoint that corresponds to January 1, 1980, I add its time argument of 47450 days to the original date of January 1, 1850. However, I get back an answer of December 1, 1979 because all the Feb. 29ths between 1850 and 1980 are excluded. Is there an additional argument in timedelta or datetime in general that deals with calendars that exclude leap days?

Upvotes: 2

Views: 940

Answers (1)

N1B4
N1B4

Reputation: 3453

netCDF num2date is the function you are looking for:

import netCDF4

ncfile = netCDF4.Dataset('./foo.nc', 'r')
time = ncfile.variables['time'] # note that we do not cast to numpy array yet
time_convert = netCDF4.num2date(time[:], time.units, time.calendar)

Note that the CMIP5 models do not have a standard calendar, so the time.calendar argument is important to include when doing this conversion.

Upvotes: 4

Related Questions