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

标签 python datetime string-formatting

我在 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')

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

最佳答案

由于 Excel 中的年份只有两位数(即 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有关日期/时间字符串格式的更多信息。

关于python - 将excel中的日期字符串转换为python中的日期对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45183293/

相关文章:

python - 尝试从 BeautifulSoup 获取元素但可能被阻止

python - 序列化包含函数的对象 - 含义

python - 将 MM-DD 添加到 Year Python

python - '%.*g' % (6,k) 在 python 中如何工作

python - Python 中的负回顾 RE

c++ - 如何从 Windows 路径的 -D 编译器定义变量创建字符串文字

python - 在 Python 中,如何对元组、字典列表中的数字列表求和?

Python 2.7 - 时间偏移转换

php - MySQL DateTime Format 用法示例?

c# - 在 C# 中将日期和时间加入 DateTime