简体   繁体   English

将月份名称和年份(例如 Jul-15)转换为日期 - Python

[英]Convert Month name and Year (Such as Jul-15) to date - Python

my column values are like this " Jul-15", "Jun-15" and etc... The data type is object.我的列值是这样的“Jul-15”、“Jun-15”等等......数据类型是对象。

I want to change the data type to date and the values to date.我想将数据类型更改为日期并将值更改为日期。 I tried我试过

df["Time Period"] = df["Time Period"].apply(lambda x: datetime.strptime(x, '%m-Y'))

but it is giving me the time data 'Jul-15' does not match format '%m-Y' .但它给了我时间数据'Jul-15' does not match format '%m-Y'

Any help is much appreciated.任何帮助深表感谢。

  • Three letters month names are matched by %b , not %m .三个字母的月份名称由%b匹配,而不是%m
  • Two digits years are matched by %y , not Y两位数年份由%y匹配,而不是Y

While you are at it, ditch .apply and use the vectorized to_datetime to gain speed:当你在做的时候, .apply并使用矢量化的to_datetime来提高速度:

df['Time Period'] = pd.to_datetime(df['Time Period'], format='%b-%y')

See strftime directives supported by pandas .请参阅pandas 支持的 strftime 指令

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM