Skip to content Skip to sidebar Skip to footer

Can't Call Strftime On Numpy.datetime64, No Definition

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

Solution 1:

Use this code:

import pandas as pd 
t= pd.to_datetime(str(date)) 
timestring = t.strftime('%Y.%m.%d')

Solution 2:

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
importdatetimet= np.datetime64('2017-10-26')
t = t.astype(datetime.datetime)
timestring = t.strftime('%Y.%m.%d')

Solution 3:

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.

Solution 4:

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:002000-01-01 00:00:002000-01-01 00:00:00
microsecond precision
2000-01-01T00:00:00.0000002000-01-01 00:00:002000-01-01 00:00:00
nanosecond precision
2000-01-01T00:00:00.0000000009466848000000000009466848000000000002000-01-01 00:00:00

Solution 5:

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.

Post a Comment for "Can't Call Strftime On Numpy.datetime64, No Definition"