Thomas
Thomas

Reputation: 491

Xarray change unit in time variable

I have a nc file in which the time variable cannot be decoded by the xarray.open_dataset() as the unit is in 'days_since_Jan11900', this is the full info from the days variable:

<xarray.DataArray 'days' (time: 87600)>
array([679352., 679353., 679354., ..., 766949., 766950., 766951.])
Dimensions without coordinates: time
Attributes:
    units:      days_since_Jan11900
    long_name:  calendar_days

I have opened the file with ds = xr.open_dataset('path/tmax_bcc-csm1-1.nc', decode_times = False), but now I would like to change the unit of the nc file into something that Python can easily decode. In my case, the time unit is for now days since Jan 01, 0000. It will eventually make it all easier for my analysis.

How can I do that?

Upvotes: 2

Views: 5321

Answers (1)

spencerkclark
spencerkclark

Reputation: 2097

To decode times, xarray searches for variables that contain a units attribute of the form "{time_unit} since {reference_date}". In your case I would override the units attribute on your DataArray, and then decode the times manually:

ds.days.attrs["units"] = "days since 0000-01-01"
result = xr.decode_cf(ds)

The one caveat, as I commented, is that I suspect the reference date you have is invalid, so decoding the times will likely raise an error.

Upvotes: 3

Related Questions