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

dee*_*eeb 13 python numpy

我有一个datetime64 t,我想表示为一个字符串.

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

AttributeError: 'numpy.datetime64' object has no attribute 'strftime'
Run Code Online (Sandbox Code Playgroud)

我错过了什么?我使用的是Python 3.4.2和Numpy 1.9.1

use*_*321 19

使用此代码:

import pandas as pd 
t= pd.to_datetime(str(date)) 
timestring = t.strftime('%Y.%m.%d')
Run Code Online (Sandbox Code Playgroud)

  • @deeb 在使用 `strftime` 之前使用 `pd.to_datetime(x)` 将对象转换为 pandas 日期时间,否则它将被视为 numpy.datetime64 (3认同)
  • 我正在这样做,但未定义 strftime (2认同)

apt*_*ryx 15

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

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

  • 这应该是公认的答案.将Pandas作为项目依赖只是为了转换日期是荒谬的. (7认同)
  • 如果将 Pandas 作为项目依赖项来_打印_日期,那就更荒谬了。 (4认同)
  • 还应该指出的是,这实际上也是一种更快的方法。使用 timeit 我发现 `t.astype(datetime.datetime).strftime('%Y.%m.%d')` 每个循环花费 5.86 µs ± 339 ns,而 `pd.to_datetime(t).strftime('%Y .%m.%d')` 每个循环花费 35.8 µs ± 252 ns。 (4认同)
  • 我同意@titusjan,但不知何故,在我的特殊情况下,我通过 t.astype(datetime.datetime) 得到了 int ,其中 np.datetime64 来自 xarray 的一部分。在我的特殊情况下,user-12321 方法更有意义。pandas 似乎对日期时间相关对象有更彻底的处理 (3认同)

Joh*_*nck 10

这是最简单的方法:

t.item().strftime('%Y.%m.%d')
Run Code Online (Sandbox Code Playgroud)

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

  • 我在 `numpy.datetime64('2021-11-01T00:00:00.000000000')` 上收到此错误:`AttributeError: 'int' 对象没有属性 'strftime' ` (7认同)

Dav*_*man 9

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

需要注意的是,它np.datetime64可能具有不同的精度。如果 t 具有纳秒精度,用户 12321 的解决方案仍然有效,但 apteryx 和 John Zwinck 的解决方案不会,因为t.astype(datetime.datetime)t.item()返回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
Run Code Online (Sandbox Code Playgroud)

  • 我已经提出了这个问题(https://github.com/numpy/numpy/issues/18363),因为它应该是一个错误。另外,获取正确日期时间的另一种方法是(丑陋的)解决方法:“t.astype('datetime64[us]').astype(datetime.datetime)”(如果您不想使用 pandas) (5认同)

adr*_*anp 5

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

  • 但是“numpy.datetime_as_string”似乎不支持输出字符串的格式,这使得它不如利用内置“datetime”对象的其他方法有用。 (3认同)