Avoiding automatic sanitization to nanoseconds in conversion to DataArray when dealing with out-of-range timestamps #6712
-
Hi!
dataset = np.asarray([1, 2, 3, 4, 5]) dataset = xr.DataArray(dataset, coords=[dates], dims=["date"]) print(dataset) I am sure there is a standard practice for using xarray with out-of-range timestamps, and I've encountered a number of similar discussions on here and StackOverflow revolving around the tangled mess of Python date and time libraries, but none of them were quite what I am looking for. I've thought of a few ways to get around this, but they require jumping through too many hoops for them to be the right way. I figure somebody on here with more experience dealing with dates and times can point me to the quickest solution. Sorry if this question is vague or ill-posed-- I'm new to this stuff, so let me know if there are any other details I should include. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
No worries -- indeed dealing with datetimes is complicated. In xarray the standard practice in this situation is to use Here is how I would use them in your example: import xarray as xr
import numpy as np
from cftime import DatetimeProlepticGregorian
from datetime import timedelta
decyrs = [1260, 1320, 1640, 1980, 2005] # years AD to convert to datetime64 objects
dates = np.empty([5],dtype="O")
for i in range(5):
start = decyrs[i] # this is the input (time in decimal years)
year = int(start)
rem = start - year
base = DatetimeProlepticGregorian(year, 1, 1)
dates[i] = base + timedelta(seconds=(base.replace(year=base.year + 1) - base).total_seconds() * rem)
dataset = np.asarray([1, 2, 3, 4, 5])
dataset = xr.DataArray(dataset, coords=[dates], dims=["date"])
where |
Beta Was this translation helpful? Give feedback.
-
Thank you so much! |
Beta Was this translation helpful? Give feedback.
No worries -- indeed dealing with datetimes is complicated. In xarray the standard practice in this situation is to use
cftime.datetime
objects (see more information in xarray's documentation here).cftime.datetime
objects are analogous to standard library datetimes, except they support both standard and non-standard calendars.Here is how I would use them in your example: