13

I have a numpy datetime.

numpy.datetime64('2010-06-01T00:00:00.000000000')

How can I get something like:

numpy.datetime64('2010-06-01')

or

'2010-06-01'

Basically, I want to remove the hour and beyond timestamp.

maximusdooku
  • 5,242
  • 10
  • 54
  • 94

3 Answers3

20

I would recommend using pandas to convert your numpy.datetime:

import pandas as pd
import numpy as np

x = np.datetime64('2010-06-01T00:00:00.000000000')
x = pd.to_datetime(x)

str(x.date())

returns:

'2010-06-01'

This can also work if you have multiple strings you want to convert:

x = [np.datetime64(i) for i in ['2010-06-01T00:00:00.000000000', '2010-12-02T00:00:00.000000000']]

x = pd.to_datetime(x)

[str(i.date()) for i in x]

returns:

['2010-06-01', '2010-12-02']
sacuL
  • 49,704
  • 8
  • 81
  • 106
15

astype works:

In [208]: d1 = numpy.datetime64('2010-06-01T00:00:00.000000000')
In [210]: d1.astype('datetime64[D]')
Out[210]: numpy.datetime64('2010-06-01')

and for the print string:

In [211]: str(d1.astype('datetime64[D]'))
Out[211]: '2010-06-01'

or editing the full string

In [216]: str(d1)
Out[216]: '2010-06-01T00:00:00.000000000'
In [217]: str(d1).split('T')[0]
Out[217]: '2010-06-01'

(earlier idea)

If you take the date out of the array, you get a datetime object. You can get the day and such as attributes:

In [198]: d=np.array('2018-03-12',dtype='datetime64[D]')
In [199]: d
Out[199]: array('2018-03-12', dtype='datetime64[D]')
In [200]: d.item()
Out[200]: datetime.date(2018, 3, 12)
In [201]: dd=d.item()
In [202]: dd.day
Out[202]: 12
In [203]: dd.month
Out[203]: 3
In [204]: dd.year
Out[204]: 2018

Simply indexing the array is not enough:

In [205]: d[()]
Out[205]: numpy.datetime64('2018-03-12')
In [206]: d[()].item()
Out[206]: datetime.date(2018, 3, 12)

From the suggested duplicate link, conversion to object dtype also creates the datetime objects:

In [207]: d.astype(object)
Out[207]: array(datetime.date(2018, 3, 12), dtype=object)

For the longer object with microseconds, item isn't as useful

In [213]: d1.item()
Out[213]: 1275350400000000000
In [214]: d1.astype('datetime64[s]').item()
Out[214]: datetime.datetime(2010, 6, 1, 0, 0)
hpaulj
  • 221,503
  • 14
  • 230
  • 353
2

Given:

>>> d=numpy.datetime64('2010-06-01T00:00:00.000000000')

You can convert to a string then partition:

>>> str(d).partition('T')
('2010-06-01', 'T', '00:00:00.000000000')

Which works even if you only have a date:

>>> d=numpy.datetime64('2010-06-01')
>>> str(d).partition('T')
('2010-06-01', '', '')
dawg
  • 98,345
  • 23
  • 131
  • 206