【问题标题】:Convert column with month and year ("August 2020"...) to datetime将带有月份和年份的列(“2020 年 8 月”...)转换为日期时间
【发布时间】:2021-09-26 10:05:32
【问题描述】:

我的数据框包含一列月份和年份作为字符串:

>>>time           index   value
   January 2021     y        5
   January 2021     v        8
   May 2020         y        25
   June 2020        Y        13
   June 2020        x        11
   June 2020        v        10
...

我想将“时间”列更改为日期时间格式,以便按时间顺序对表格进行排序。
当时间是带有月份名称和数字的字符串时,有什么办法吗?

#编辑: 当我这样做时:

result_Table['time']=pd.to_datetime(result_Table['time'],format='%Y-%m-%d')

我收到错误:

ValueError:2021 年 1 月的时间数据与指定的格式不匹配

【问题讨论】:

  • df['time']=pd.to_datetime(df['time'])?
  • @AnuragDabas 我收到错误:ValueError:2021 年 1 月的时间数据与指定的格式不匹配

标签: python pandas string datetime


【解决方案1】:

示例数据框:

df=pd.DataFrame({'time':['January 2021','May 2020','June 2020']})

如果你想指定格式参数,那么应该是'%B %Y' 而不是'%Y-%m-%d'

df['time']=pd.to_datetime(df['time'],format='%B %Y')
#OR
#you can also simply use:
#df['time']=pd.to_datetime(df['time'])

df 的输出:

    time
0   2021-01-01
1   2020-05-01
2   2020-06-01

有关格式代码的更多信息visit here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    相关资源
    最近更新 更多