Skip to content

Convert decimal years to datetime64 data #6868

Closed Answered by andersy005
mgorfer asked this question in Q&A
Discussion options

You must be logged in to vote

@mgorfer,

it's my understanding that the time units units: year A.D. don't follow CF conventions. Consequently, xarray doesn't know how to decode these values out of the box. One solution is to convert your decimal values into datetime objects. The following code snippet is adapted from this Stackoverflow post

In [30]: def decimal_to_datetime(value):
    ...:     year = int(value)
    ...:     remainder = value - year
    ...:     base = datetime.datetime(year , 1, 1)
    ...:     result = base + datetime.timedelta(seconds=(base.replace(year=base.year + 1) - base).total_seconds() * remainder)
    ...:     return result
    ...: 

In [31]: decimal_to_datetime(1850.041667)
Out[31]: datetime.d…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@mgorfer
Comment options

@andersy005
Comment options

Answer selected by mgorfer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
2 participants