【问题标题】:'str' object has no attribute 'strftime'“str”对象没有属性“strftime”
【发布时间】:2019-03-05 03:52:58
【问题描述】:

我的脚本中出现此错误

'str' 对象没有属性'strftime'

df.set_index('Profile_ID', inplace=True)
df['CohortGroup'] = df.groupby(level=0)['Date_of_Service_Requested'].min().apply(lambda x: x.strftime('%Y-%m')) 
df.reset_index(inplace=True)
df.head()

【问题讨论】:

    标签: python string date datetime strftime


    【解决方案1】:

    strftimedatetime 方法,而不是 str 方法。您可以使用pd.to_datetime 创建一个datetime 系列:

    import pandas as pd
    df = pd.DataFrame({'date_column': ['2019-03-15', '2016-12-05'],
                       'other_column': [10, 4]})
    df['date_column'] = pd.to_datetime(arg=df['date_column'], 
                                       format='%Y-%m-%d')
    df['date_column'].apply(lambda x: x.strftime('%Y-%m'))
    

    【讨论】:

      猜你喜欢
      • 2013-11-22
      • 2021-10-12
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-11
      • 2015-09-11
      • 2020-04-07
      相关资源
      最近更新 更多