Skip to main content
 首页 » 编程设计

python之将 excel 中的日期字符串转换为 python 中的日期对象

2024年10月01日27三少

我在 excel 中有一个日期,格式为:dd mmm yy 格式即,

29 Jun 18

如何将此字符串转换为日期对象?

我得到错误:

time data '13 Jul 18' does not match format '%d %m %Y'  

当我尝试

datetime.strptime(input, '%d %m %Y') 

正确的日期格式应该是什么?

请您参考如下方法:

由于您的 excell 中的年份只有两位数(即 18 而不是 2018),因此您需要在格式字符串中使用 %y 而不是 %Y:

datetime.strptime(input, '%d %b %y') 

例如:

datetime.strptime( '13 Jul 18', '%d %b %y') 

结果:

datetime.datetime(2018, 7, 13, 0, 0) 

参见 this page有关日期/时间字符串格式的更多信息。