我收到错误
'str' object has no attribute 'strftime'
来 self 的这段代码:
from datetime import datetime, date
analysis_dataframe.loc[:,'order_period'] = analysis_dataframe.date.apply(lambda x: x.strftime('%Y-%m'))
analysis_dataframe.head(10)
我有一个“日期”列,其日期格式如下:
如何修复此错误?
谢谢
最佳答案
strftime
是datetime
类的成员函数。
您在 x 上调用了该函数:x.strftime('%Y-%m')
。错误消息表明 x 是 str
类型的对象,即它是一个字符串。
看起来您的analysis_dataframe.date
是格式化日期时间字符串的数组/系列,而不是实际的日期时间。
因此,为了使用strftime函数,需要先将日期字符串解析为datetime
对象,然后调用strftime函数:
... = analysis_dataframe.date.apply(lambda x: datetime.fromisoformat(x).strftime('%Y-%m'))
关于python - 获取错误 AttributeError : 'str' object has no attribute 'strftime' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68699116/