skyfielders / python-skyfield

Elegant astronomy for Python
MIT License
1.38k stars 208 forks source link

Compatibility with numpy datetime arrays? #891

Closed toihr closed 10 months ago

toihr commented 10 months ago

There does not seem to be a compatibility with numpy datetime. Whenever you obtain UTC or another array from a Time object you always get a numpy array of datetime objects. It could be useful to have this in a numpy datetime array.

brandon-rhodes commented 10 months ago

NumPy datetimes, alas, don't properly handle leap seconds and so would return wrong numbers of seconds between astronomical events that happen to span a leap second. It also means that no linear count of time that's kept in the Skyfield Time object could be directly converted into a NumPy datetime64, because it would go off by one second each time a leap second passed.

But there's one Skyfield method you could use that returns a fake approximate time scale that ignores leap seconds: the t.toordinal() method. Here's how you could use it:

import numpy as np
from skyfield.api import load

ts = load.timescale()
t = ts.utc(2023, 8, 15, 7, 3)

seconds = int(round(t.toordinal() * 86400))
dt = np.datetime64('0-12-31') + np.timedelta64(seconds, 's')
print(dt)

Given the shortcomings of NumPy's datetime64, I don't think there's any value in Skyfield supporting them directly; but hopefully folks can use this example code if they find themselves in a situation where they need to do a conversion!

I'm going to close this since I'm not expecting to add code to Skyfield, but please feel free to follow up with further comments if your project is blocked on the problem of conversions to datetime64, and you need to ask more questions!