22from __future__ import division
33from __future__ import print_function
44
5- from .common import is_datetime_like
5+ from .common import is_np_datetime_like , _contains_datetime_like_objects
66from .pycompat import dask_array_type
77
88from functools import partial
@@ -20,6 +20,20 @@ def _season_from_months(months):
2020 return seasons [(months // 3 ) % 4 ]
2121
2222
23+ def _access_through_netcdftimeindex (values , name ):
24+ """Coerce an array of datetime-like values to a NetCDFTimeIndex
25+ and access requested datetime component
26+ """
27+ from ..conventions .netcdftimeindex import NetCDFTimeIndex
28+ values_as_netcdftimeindex = NetCDFTimeIndex (values )
29+ if name == 'season' :
30+ months = values_as_netcdftimeindex .month
31+ field_values = _season_from_months (months )
32+ else :
33+ field_values = getattr (values_as_netcdftimeindex , name )
34+ return field_values .reshape (values .shape )
35+
36+
2337def _access_through_series (values , name ):
2438 """Coerce an array of datetime-like values to a pandas Series and
2539 access requested datetime component
@@ -52,12 +66,17 @@ def _get_date_field(values, name, dtype):
5266 Array-like of datetime fields accessed for each element in values
5367
5468 """
69+ if is_np_datetime_like (values .dtype ):
70+ access_method = _access_through_series
71+ else :
72+ access_method = _access_through_netcdftimeindex
73+
5574 if isinstance (values , dask_array_type ):
5675 from dask .array import map_blocks
57- return map_blocks (_access_through_series ,
76+ return map_blocks (access_method ,
5877 values , name , dtype = dtype )
5978 else :
60- return _access_through_series (values , name )
79+ return access_method (values , name )
6180
6281
6382class DatetimeAccessor (object ):
@@ -83,9 +102,11 @@ class DatetimeAccessor(object):
83102
84103 """
85104 def __init__ (self , xarray_obj ):
86- if not is_datetime_like (xarray_obj . dtype ):
105+ if not _contains_datetime_like_objects (xarray_obj ):
87106 raise TypeError ("'dt' accessor only available for "
88- "DataArray with datetime64 or timedelta64 dtype" )
107+ "DataArray with datetime64 timedelta64 dtype or "
108+ "for arrays containing netcdftime datetime "
109+ "objects." )
89110 self ._obj = xarray_obj
90111
91112 def _tslib_field_accessor (name , docstring = None , dtype = None ):
@@ -147,4 +168,4 @@ def f(self, dtype=dtype):
147168
148169 time = _tslib_field_accessor (
149170 "time" , "Timestamps corresponding to datetimes" , object
150- )
171+ )
0 commit comments