How do I get the UNIX time from a numpy.datetime64 or numpy.datetime_?
As in for example:
np.datetime_('2012-08-08 13:37:00')
Step 2: Create a Sample date in the format datetime64. Then an array of datetime64 type. After that, You can create datetime64 format using the numpy. datetime64() format. To convert it to datetime format then you have to use astype() method and just pass the datetime as an argument.
datetime64() method, we can get the date in a numpy array in a particular format i.e year-month-day by using numpy. datetime64() method. Syntax : numpy.datetime64(date) Return : Return the date in a format 'yyyy-mm-dd'.
Pandas Convert Date to String Format – To change/convert the pandas datetime ( datetime64[ns] ) from default format to String/Object or custom format use pandas. Series. dt. strftime() method.
The Unix timestamp is a single signed integer that grows by one every second, allowing computers to store and manipulate conventional date systems. The software is then translated into a human-readable format. The Unix timestamp is the number of seconds calculated since January 1, 1970.
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.
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....
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With