3

I have a data array arr with coordinate 'time'. arr:

    <xarray.DataArray 'T' (time: 731)>
array([244.40161, 244.39998, ..., 244.40936, 244.40549], dtype=float32)
Coordinates:
  * time         (time) datetime64[ns] 1979-01-01T09:00:00 ... 1980-12-31T09:00:00

Extracting the first 5 time coordinates, arr.time.values[:5]:

array(['1979-01-01T09:00:00.000000000', '1979-01-02T09:00:00.000000000',
       '1979-01-03T09:00:00.000000000', '1979-01-04T09:00:00.000000000',
       '1979-01-05T09:00:00.000000000'], dtype='datetime64[ns]')

I want the format of my date-time to just be '1979-01-01', '1979-01-02' etc. without the time, or normalise the time at 00:00:00.

There are some solutions for pandas data frame but I'm not quite sure how to apply them here since the functions aren't applicable (Converting between datetime, Timestamp and datetime64, Keep only date part when using pandas.to_datetime)

ru111
  • 813
  • 3
  • 13
  • 27

1 Answers1

6

There are a few ways you can do this. The quick and dirty way I often use is uses resample:

da.resample(time='1D').first()

Something that is a bit more robust would be modify the time index directly:

da['time'] = da.indexes['time'].normalize()

Finally, this can be done generally by creating a new datetime index:

da['time'] = pd.date_range(da['time'][0], periods=len(da['time']), freq='1D')

Note that the second and third examples are going to be computationally cheaper than the first but does require working directly with the underling Pandas index.

jhamman
  • 5,867
  • 19
  • 39
  • 1
    Many thanks - this is a neat direct way as it doesn't require converting into a dataframe first etc., `arr['time'] = arr.indexes['time'].normalize()` worked perfectly where `arr` is an xarray data array. What is the difference between the second and third example you gave? – ru111 Feb 14 '19 at 15:28
  • In this case, my 2nd and 3rd examples are basically the same operation. The third is a bit more extensible as you could use it to replace any existing time index. – jhamman Feb 14 '19 at 19:48