Converting Astropy.time.Time to datetime: Leapseconds

As Astropy.time.Time supports leap seconds and datetime does not, attempting to convert (Time.datetime) throws a value error:

ValueError: Time (array(2016, dtype=int32), array(12, dtype=int32), array(31, dtype=int32), array(23), array(59), array(60), array(993683)) is within a leap second but datetime does not support leap seconds

I can see why this should be the default behaviour. But is there any optional flag to get Time to ignore this and just convert to closest datetime? I couldn’t find anything in the docs.

There is no such flag to ignore that exception. One option would be using the ymdhms format to do your own adjustments to ensure all the date values are legal for datetime and then initialize from your cleaned arrays.

1 Like

Yeah, ok, thanks. Obviously I can do a workaround.

But it kind of makes the time.datetime method somewhat redundant if you always need to check it’s not going throw a valueerror and crash your code. If there’s no option to ignore, would a warning not be better?

That’s not a bad idea. Maybe just clip the seconds at < 60 and warn?

Sounds like a good compromise to me! I can’t think of a better way of doing it.

See Add strict arg to Time.to_datetime() for leap second handling by taldcroft · Pull Request #14606 · astropy/astropy · GitHub.

1 Like

Perfect. Thanks. A nice and tidy solution.