Search code examples
pythonnumpyunix-timestamp

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


Solution

  • 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]