Seconds (or minutes or hours etc.) are time differences, i.e. timedelta, so another approach is to cast the seconds into a timedelta
object and add it to the UNIX epoch (which is 1970-01-01 00:00:00 UTC).
from datetime import datetime, timedelta, UTC
# for UTC datetime
datetime.fromtimestamp(0, UTC) + timedelta(seconds=1284286794)
# ^^^^^ UNIX epoch
# for naive datetime
datetime.fromtimestamp(0) + timedelta(seconds=1284286794)
This approach works for timestamps before the epoch (i.e. negative seconds) as well, unlike directly passing a negative number to fromtimestamp
, which raises an OSError (at least on Windows).
datetime.fromtimestamp(0, UTC) + timedelta(seconds=-1284286794)
On a somewhat related note, if you're already using numpy, then you can use np.datetime64
to cast integers into datetimes as well. The integers are interpreted as offsets relative to the UNIX epoch. You just need to pass the unit using [s]
(for seconds). Nice thing about numpy is that you can cast an entire list of seconds into an array of datetimes vectorially.
np.array([1284286794, 0, -1284286794], dtype='datetime64[s]')