4

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,775
  • 3
  • 18
  • 40

3 Answers3

4
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
  • 13,096
  • 12
  • 42
  • 54
  • 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
  • thanks, i also needed this, for the time part of the datetime64, as a string, so it's more convenient, if a string "13:20:06" is what you want. Btw, one could also call str(t) or t.__str__() directly to get the string, then apply the slicing... – vuvu Jun 13 '23 at 15:54
4

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
  • 13,096
  • 12
  • 42
  • 54
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)
Niko Föhr
  • 28,336
  • 10
  • 93
  • 96