Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode the time variable while using xarray to load a NETCDF file

I have a netcdf file giving monthly precipitation values from 1948 to 2008. The time variable has a format as below:

float time(time) ;
        time:units = "months since 1948-01-01 00:00:00" ;
        time:time_origin = "01-JAN-1948:00:00:00" ;

When i try to use Xarray to open the dataset using the following command

ds=xr.open_dataset("C:/Users/vsri/Downloads/prcp_monthly_1948-2008.nc")

I get the following error

ValueError: unable to decode time units 'months since 1948-01-01 00:00:00' with the default calendar. Try opening your dataset with decode_times=False.

If i use the decode_Times=False argument, the time variable has a floating point value assigned to it (as below)

 Coordinates:
      * longitude  (longitude) float32 0.25 0.75 1.25 1.75 ... 358.75 359.25 359.75
      * latitude   (latitude) float32 -89.75 -89.25 -88.75 ... 88.75 89.25 89.75
      * z       (z) float32 0.0
      * time (time) float32 0.0 1.0 2.0 3.0 4.0 ... 728.0 729.0 730.0 731.0

I do not want to use decode_Times=False becasue I cannot use the resample function of xarray on the dataset any more.

Can someone guide me on how to make sure that xarray reads the data set with the proper time stamp and not as a floating point ?

like image 433
Vignesh Sridharan Avatar asked Aug 28 '26 17:08

Vignesh Sridharan


1 Answers

Thanks for the update in your comment. In your case, since your data has a regular frequency, I recommend working around this by creating your own time coordinate with pandas.date_range:

import pandas as pd
import xarray as xr

ds = xr.open_dataset("C:/Users/vsri/Downloads/prcp_monthly_1948-2008.nc", decode_times=False)
units, reference_date = ds.time.attrs['units'].split('since')
ds['time'] = pd.date_range(start=reference_date, periods=ds.sizes['time'], freq='MS')

This will create an array of dates for the first of each month starting in 1948-01-01 and ending the appropriate number of months later.

like image 113
spencerkclark Avatar answered Aug 31 '26 02:08

spencerkclark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!