2

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

Ach113
  • 1,550
  • 2
  • 14
  • 34

3 Answers3

3

Convert it to the pandas Timestamp object:

import pandas as pd

t1 = pd.Timestamp(t)

and then you may use

t1.hour
t1.minute
t1.second

(and similar for year, month, day, etc.) to obtain individuals items from it.

MarianD
  • 11,249
  • 12
  • 32
  • 51
2
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.

MarianD
  • 11,249
  • 12
  • 32
  • 51
  • why this if you provide a much more [elegant solution](https://stackoverflow.com/a/61407267/10197418)? – FObersteiner Apr 24 '20 at 12:02
  • 2
    @MrFuppes, 'cos I like alternatives. :-) The other reason is that not everyone with installed NumPy has installed pandas, too. – MarianD Apr 24 '20 at 15:52
0

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)
np8
  • 20,899
  • 9
  • 73
  • 87