我有一个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)
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)
Joh*_*nck 10
这是最简单的方法:
t.item().strftime('%Y.%m.%d')
Run Code Online (Sandbox Code Playgroud)
item() 为您提供一个 Python 本机日期时间对象,在该对象上可以使用所有常用方法。
如果您的目标只是表示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)
对于那些可能偶然发现这一点的人:numpy 现在有一个numpy.datetime_as_string函数。唯一需要注意的是它接受一个数组而不仅仅是一个单独的值。然而,我可以认为这仍然是一个比必须使用另一个库来进行转换更好的解决方案。