【问题标题】:TypeError: descriptor 'strftime' for 'datetime.date' objects doesn't apply to a 'str' objectTypeError:“datetime.date”对象的描述符“strftime”不适用于“str”对象
【发布时间】:2021-10-26 13:16:56
【问题描述】:

我有一个数据框

timestamp
2020-08-26
2020-08-27
2020-08-28

我希望它看起来像这样

timestamp
2020-08-26 00:00:00
2020-08-27 00:00:00
2020-08-28 00:00:00

我试过了

df['timestamp'] = df['timestamp'].apply(lambda x: dt.datetime.strftime(x, '%Y-%m-%d %H:%M:%S'))

但它给出了一个问题 TypeError: descriptor 'strftime' for 'datetime.date' objects does not apply to a 'str' object

感谢您的帮助

【问题讨论】:

标签: python python-3.x pandas dataframe datetime


【解决方案1】:

试试这个,

df['timestamp'] = pd.to_datetime(df['timestamp']).dt.strftime('%Y-%m-%d %H:%M:%S')

【讨论】:

  • TypeError: 无法转换输入 [99 2021-04-06 98 2021-04-07 97 2021-04-08 96 2021-04-09 95 2021-04-12 ... 4 2021- 08-19 3 2021-08-20 2 2021-08-23 1 2021-08-24 0 2021-08-25 名称:时间戳,长度:100,dtype:object]类型为到时间戳
  • 发生另一个错误 AttributeError: Can only use .dt accessor with datetimelike values
【解决方案2】:

试试这个:

df1 = pd.DataFrame({'time': {0: '2020-08-26', 1: '2020-08-27', 2: '2020-08-28'}})

df1.time = pd.to_datetime(df1.time, format="%Y-%m-%d %H:%M:%S")


df1['time'].apply(lambda x : datetime.strptime(str(x), "%Y-%m-%d %H:%M:%S"))

list(map(str, df1.time))

输出:

['2020-08-26 00:00:00', '2020-08-27 00:00:00', '2020-08-28 00:00:00']

【讨论】:

  • 它没有工作,仍然没有时间和秒
  • @yanbiceps,我编辑了代码块,这是你的答案吗?
  • 什么是 datetime 是 dt.datetime?
  • @yanbiceps,我不使用dt.datetime
  • 是的,谢谢,但@anarchy 方法更短但很有用
猜你喜欢
  • 2020-11-01
  • 2022-01-21
  • 1970-01-01
  • 2020-03-18
  • 1970-01-01
  • 2021-09-14
  • 2022-11-26
  • 1970-01-01
  • 2020-06-30
相关资源
最近更新 更多