无法在 numpy.datetime64 上调用 strftime,没有定义

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

我有一个 datetime64 t,我想将其表示为一个字符串。

当我这样调用 strftime 时 t.strftime('%Y.%m.%d') 我得到这个错误:

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

我错过了什么?我正在使用 Python 3.4.2 和 Numpy 1.9.1

使用此代码:

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

导入像 pandas 这样的数据结构库来完成类型转换对我来说感觉有点过分了。您可以使用标准日期时间模块实现相同的目的:

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

这是最简单的方法:

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

item() 为您提供了一个 Python 原生日期时间对象,在该对象上可以使用所有常用方法。

如果您的目标只是将 t 表示为字符串,最简单的解决方案是 str(t)。如果您想要特定格式,您应该使用上述解决方案之一。

需要注意的是 np.datetime64 可以有不同的精度。如果 t 具有纳秒精度,用户 12321 的解决方案仍然有效,但 apteryx 和 John Zwinck 的解决方案不会,因为 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

对于那些可能偶然发现这一点的人:numpy 现在有一个 numpy.datetime_as_string 函数。唯一需要注意的是它接受一个数组而不仅仅是一个单独的值。然而,我可以说这仍然是一个比仅使用另一个库来进行转换更好的解决方案。

将日期时间对象转换为字符串并使用拆分可能会有所帮助,如下所示:

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

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

print(dtString)

>>> '2011-08-01'