Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to convert from a unixtime to a numpy.datetime64?

I suppose that the key here is to have the less number of intermediate conversions but I'm not able to find a simple way in the new Numpy 2.0 dev

like image 422
tonicebrian Avatar asked Oct 30 '25 01:10

tonicebrian


1 Answers

Actually, numpy.datetime64 objects are basically unix times internally (with 6 extra significant digits to account for millisecond precision). You just need to multiply by 1e6.

As an example:

import numpy as np

# Generate a few unix time stamps near today...
x = np.arange(1326706251, 1326706260)

# Convert to datetimes...
x *= 1e6
x = x.view(np.datetime64)

print x

This yields:

[2012-01-16 09:30:51 2012-01-16 09:30:52 2012-01-16 09:30:53
 2012-01-16 09:30:54 2012-01-16 09:30:55 2012-01-16 09:30:56
 2012-01-16 09:30:57 2012-01-16 09:30:58 2012-01-16 09:30:59]
like image 58
Joe Kington Avatar answered Nov 01 '25 15:11

Joe Kington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!