Reputation: 1
I have an large 2D array contains seconds from year 2000, I want to convert to an array of datetime. I could not find a good way to do it. I used a loop. But it did not work and it produced an error as: TypeError: float() argument must be a string or a number, not 'datetime.datetime'
I give the example code as below. Would you please give me any suggestions? Thank you.
import numpy as np
import datetime as dt
secs_from_2000 = np.array([[6.833232e+08, 6.833233e+08, 6.833235e+08], [6.833239e+08, 6.833242e+08, 6.833244e+08]])
dt_from_1970 = np.empty_like(secs_from_2000)
for i in range(secs_from_2000.shape[0]):
for j in range(secs_from_2000.shape[1]):
dt_from_1970[i,j] = dt.datetime.utcfromtimestamp((dt.datetime(2000,1,1)- dt.datetime(1970,1,1)).total_seconds() + secs_from_2000[i,j])
Upvotes: 0
Views: 159
Reputation: 522
There are three parts of this problem:
For 1, if we call the "seconds from 2000" figure t'
, and the standard Unix time is t
, you can see that t - t' = x
where x
is a constant adjustment factor, such that t = t' + x
(t'
is what you have, t
is what you want). Moreover, x
is equal to the number of seconds between 1970 and 2000. Thus you can calculate it with:
>>> from datetime import datetime
>>> datetime(year=2000, month=1, day=1).timestamp()
946710000.0
Now you just have to add this to your t'
:
def unix_time(secs_from_2000: float) -> float:
return secs_from_2000 + 946710000
For 3, I believe this is covered in Apply function to all elements in NumPy matrix so I won't duplicate it here.
Upvotes: 1