How to get unix timestamp from numpy.datetime64

In order to account for the units, I think you need to do something like:

def get_unixtime(dt64):
    return dt64.astype('datetime64[s]').astype('int')

Note that this converts to 'seconds' (the [s]) prior to converting to integers. This works on NumPy 1.12.1.


I get inconsistent results for the value of np.datetime64('now') on numpy 1.6.1 vs. 1.7.

This works on both:

>>> import datetime
>>> import numpy as np
>>> now = np.datetime64(datetime.datetime.now())
>>> (now.astype('uint64') / 1e6).astype('uint32')
1344447810

numpy datetime64 has variable units:

Extracted from official doc:

The unit for internal storage is automatically selected from the form of the string, and can be either a date unit or a time unit. The date units are years (‘Y’), months (‘M’), weeks (‘W’), and days (‘D’), while the time units are hours (‘h’), minutes (‘m’), seconds (‘s’), milliseconds (‘ms’), and some additional SI-prefix seconds-based units.

So, first we need to check the current unit using dtype, for example:

>>> now = np.datetime64(datetime.datetime.now())
>>> now.dtype

# for ns unit, use:
dtype('<M8[ns]')
now.astype('int64')/1e9, dtype='int32'

# for us unit, use:
dtype('<M8[us]')
now.astype('int64')/1e6, dtype='int32'

# for ms unit, use:
dtype('<M8[ms]')
now.astype('int64')/1e3, dtype='int32'

and so on....

Tags:

Python

Numpy