Can't call strftime on numpy.datetime64, no definition

Question:

I have a datetime64 t that I’d like to represent as a string.

When I call strftime like this t.strftime('%Y.%m.%d') I get this error:

AttributeError: 'numpy.datetime64' object has no attribute 'strftime'

What am I missing? I am using Python 3.4.2 and Numpy 1.9.1

Asked By: deeb

||

Answers:

Use this code:

import pandas as pd 
t= pd.to_datetime(str(date)) 
timestring = t.strftime('%Y.%m.%d')
Answered By: user 12321

Importing a data structures library like pandas to accomplish type conversion feels like overkill to me. You can achieve the same thing with the standard datetime module:

import numpy as np
import datetime
t = np.datetime64('2017-10-26')
t = t.astype(datetime.datetime)
timestring = t.strftime('%Y.%m.%d')
Answered By: apteryx

This is the simplest way:

t.item().strftime('%Y.%m.%d')

item() gives you a Python native datetime object, on which all the usual methods are available.

Answered By: John Zwinck

If your goal is only to represent t as a string, the simplest solution is str(t). If you want it in a specific format, you should use one of the solutions above.

One caveat is that np.datetime64 can have different amounts of precision. If t has nanosecond precision, user 12321’s solution will still work, but apteryx’s and John Zwinck’s solutions won’t, because t.astype(datetime.datetime) and t.item() return an int:

import numpy as np

print('second precision')
t = np.datetime64('2000-01-01 00:00:00') 
print(t)
print(t.astype(datetime.datetime))
print(t.item())

print('microsecond precision')
t = np.datetime64('2000-01-01 00:00:00.0000') 
print(t)
print(t.astype(datetime.datetime))
print(t.item())

print('nanosecond precision')
t = np.datetime64('2000-01-01 00:00:00.0000000') 
print(t)
print(t.astype(datetime.datetime))
print(t.item())
import pandas as pd 
print(pd.to_datetime(str(t)))


second precision
2000-01-01T00:00:00
2000-01-01 00:00:00
2000-01-01 00:00:00
microsecond precision
2000-01-01T00:00:00.000000
2000-01-01 00:00:00
2000-01-01 00:00:00
nanosecond precision
2000-01-01T00:00:00.000000000
946684800000000000
946684800000000000
2000-01-01 00:00:00
Answered By: David Wasserman

For those who might stumble upon this: numpy now has a numpy.datetime_as_string function. Only caveat is that it accepts an array rather than just an individual value. I could make however that this is still a better solution than having to use another library just to do the conversion.

Answered By: adrianp

It might help to convert the datetime object to string and use splitting as shown below:

dtObj = 2011-08-01T00:00:00.000000000

dtString = str(dtObj).split('-01T00:00:00.000000000')[0]

print(dtString)

>>> '2011-08-01'

Answered By: moinabyssinia
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.