-
-
Save vn-ki/01b6d32b7a255e796ea54e8b882c8512 to your computer and use it in GitHub Desktop.
Example gist showing how to convert numpy.datetime64 to astropy.Time for the use of sunpy.time.parse_time. Another (better?) example at https://gist.github.com/vn-ki/28edbc581b1218118b40df29855d1c6c.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Example implementaion of parse_time to convert numpy.datetime64 to astropy.Time | |
""" | |
import numpy as np | |
from functools import singledispatch | |
from astropy import units as u | |
from astropy.time import Time | |
from datetime import datetime | |
# The logic is taken from here: | |
# https://github.com/astropy/astropy/issues/6428#issuecomment-362224248 | |
DATETIME64_TO_UNIT = { | |
'datetime64[W]': u.week, | |
'datetime64[D]': u.day, | |
'datetime64[h]': u.hour, | |
'datetime64[s]': u.second, | |
'datetime64[ms]': u.millisecond, | |
'datetime64[us]': u.microsecond, | |
'datetime64[ns]': u.nanosecond, | |
'datetime64[ps]': u.picosecond, | |
'datetime64[fs]': u.femtosecond, | |
'datetime64[as]': u.attosecond, | |
} | |
@singledispatch | |
def convert_time(time_string): | |
return time_string # This is incomplete becuase it is an example | |
@convert_time.register(np.datetime64) | |
def convert_time_npdatetime(time_string): | |
""" | |
Handle when time_string is np.datetime64 | |
""" | |
if time_string.dtype.name in ['datetime64[M]', 'datetime64[Y]']: | |
time_string = time_string.astype('M8[D]') | |
return Time( | |
time_string.view('i8') * DATETIME64_TO_UNIT[time_string.dtype.name], | |
format='unix') | |
@convert_time.register(np.ndarray) | |
def convert_time_ndarray(time_string): | |
""" | |
Handle when time_string is np.datetime64 | |
""" | |
# Another way to do this would be: | |
# return Time([convert_time_npdatetime(dt) for dt in time_string]) | |
# astropy.Time supports arrays | |
return np.array([convert_time_npdatetime(dt) for dt in time_string]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment