1

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?

Asblut
  • 13
  • 1
  • 4

1 Answers1

5

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
Dan
  • 1,105
  • 12
  • 15
  • 1
    OMG, such a simple solution. Why didn't i think of that? Thanks Dan! – Asblut Jun 29 '20 at 06:06
  • Glad to help, if this answer solved your problem please mark it as accepted by clicking the check mark next to the answer. See: [How does accepting an answer work?](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) for more info. – Dan Jun 29 '20 at 16:59
  • @Dan do you mind explaining why this is necessary? When I do `pd.to_xarray()`, my dataframe contains `datetime64`, but the xarray output contains `pd.Timestamp` objects. It's not clear why a recast is happening. – cjm2671 Sep 16 '21 at 19:35
  • 1
    I needed to execute the same twice. In first execution it was still obejct (seemed like big number) and then in the second time it was converted to datetime64 object. – Vinod Kumar Apr 19 '22 at 22:21