'How to extract hours/minutes/seconds from np.datetime64

I have a datetime object that looks like this:

t = numpy.datetime64('2020-04-15T13:20:06.810000000') From it I want to extract only 13:20:06. How can I do this?

All answers on SO on similar questions that I have found suggested using t.hour or t.minute. But when I attempt doing it I get an AttributeError, saying that np.datetime64 object has no such attributes



Solution 1:[1]

t.astype(str)[11:19]
'13:20:06'

The explanation:

t.astype(str) changes your object to the string of the fixed format:

'2020-04-15T13:20:06.810000000'

so you may then select the part of your interest.

Solution 2:[2]

You can do this also just by using the datetime from the standard library. It is also about 40% faster than using pandas, or 80% faster than converting to string:

import datetime as dt
import numpy as np 

t = np.datetime64("2020-04-15T13:20:06.810000000")
t1 = dt.datetime.utcfromtimestamp(t.tolist() / 1e9)

Example output

In [47]: t = np.datetime64("2020-04-15T13:20:06.810000000")

In [48]: t1 = dt.datetime.utcfromtimestamp(t.tolist() / 1e9)

In [49]: t1.hour
Out[49]: 13

In [50]: t1.minute
Out[50]: 20

In [51]: t1.second
Out[51]: 6

Speed comparison for extracting just hour

In [41]: dt.datetime.utcfromtimestamp(t.tolist() / 1e9).hour
Out[41]: 13

In [42]: pd.Timestamp(t).hour
Out[42]: 13

In [43]: int(t.astype(str)[11:13])
Out[43]: 13

In [44]: %timeit dt.datetime.utcfromtimestamp(t.tolist() / 1e9).hour
760 ns ± 23.2 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)

In [45]: %timeit pd.Timestamp(t).hour
1.22 µs ± 14 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)

In [46]: %timeit int(t.astype(str)[11:13])
3.59 µs ± 48.9 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MarianD
Solution 2 np8