Skip to content

Commit 2f60e2f

Browse files
Added explicit conversion to np.datetime64[ns] when time input is a pandas Series() or xarray DataArray
Added logic to convert timezone-aware Python datetimes to np.datetime64 without warnings
1 parent 96f5c4a commit 2f60e2f

1 file changed

Lines changed: 10 additions & 5 deletions

File tree

pyspedas/tplot_tools/store_data.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import xarray as xr
1313
import copy
1414
import warnings
15+
from pyspedas import is_timezone_aware
1516

1617
tplot_num = 1
1718

@@ -161,11 +162,16 @@ def store_data(name, data=None, delete=False, newname=None, attr_dict={}):
161162

162163
# Convert input time representation to np.datetime64 objects, if needed
163164
if isinstance(times, pd.Series):
164-
logging.warning('store_data: unchecked conversion of pd.Series to numpy times')
165-
datetimes = times.to_numpy() # if it is pandas series, convert to numpy array
165+
datetimes = times.to_numpy(dtype='datetime64[ns]') # if it is pandas series, convert to numpy array
166166
elif isinstance(times[0],datetime.datetime):
167167
# Timezone-naive datetime, do explicit conversion to np.datetime64[ns] and ensure container is a numpy array
168-
if isinstance(times,np.ndarray):
168+
if is_timezone_aware(times):
169+
# Numpy will complain if it is given timezone-aware datetimes to convert.
170+
# So we convert to UTC first, then drop the timezone entirely
171+
tz_aware_utc = [aware_dt.astimezone(datetime.timezone.utc) for aware_dt in times]
172+
tz_naive = [aware_dt.replace(tzinfo=None) for aware_dt in tz_aware_utc]
173+
datetimes = np.array(tz_naive,dtype='datetime64[ns]')
174+
elif isinstance(times,np.ndarray):
169175
datetimes = times.astype('datetime64[ns]')
170176
else:
171177
datetimes = np.array(times,dtype='datetime64[ns]')
@@ -195,8 +201,7 @@ def store_data(name, data=None, delete=False, newname=None, attr_dict={}):
195201
datetimes = np.array(times,dtype='datetime64[ns]')
196202
else:
197203
# Hope it's convertable to a numpy array! This case will get hit for an xarray DataArray.
198-
logging.warning('store_data: unchecked conversion of xarray? to numpy times')
199-
datetimes = np.array(times)
204+
datetimes = np.array(times).astype('datetime64[ns]')
200205

201206
times = datetimes
202207

0 commit comments

Comments
 (0)