Search code examples
python-xarraynetcdf4datetimeindex

xarray: coords conversion to datetime64


I have a NetCDF4 file that i'm handling using xarray. The dataset has a "time" coordinate as dtype=object and i would like to convert it ot datetime64 in order to simplify plotting of the variables contained in the file. My plan was to create a new time coordinate called "time1" using

ds.assign_coords(time1=pd.to_datetime(ds.time.values,infer_datetime_format=True))

and then delete the old one. But i get a new coordinate still as dtype=object. here's how the new dataset looks like

What am i doing wrong?


Solution

  • Problems like this can often be solved with something like:

    ds['time'] = pd.DatetimeIndex(ds['time'].values)

    Here's an example, prior to applying the above line:

    <xarray.Dataset>
    Dimensions:  (time: 93)
    Coordinates:
      * time     (time) object 1593128700000000000 ... 1593211500000000000
    Data variables:
        val      (time) float64 4.23 4.25 4.24 4.23 4.24 ... 4.08 4.07 4.07 4.07
    

    and after:

    <xarray.Dataset>
    Dimensions:  (time: 93)
    Coordinates:
      * time     (time) datetime64[ns] 2020-06-25T23:45:00 ... 2020-06-26T22:45:00
    Data variables:
        val      (time) float64 4.23 4.25 4.24 4.23 4.24 ... 4.08 4.07 4.07 4.07