Python 将带有月份名称的字符串转换为日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42980662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:21:21  来源:igfitidea点击:

Convert String with month name to datetime

pythondatetime

提问by Arjun

I'm using pickadate.jswhich returns the date in this format:

我正在使用pickadate.jswhich 以这种格式返回日期:

8 March, 2017

I would like to convert this to the datetimeformat of:

我想将其转换为以下datetime格式:

yyyy-mm-dd

What would be the best way to do this in Python?

在 Python 中执行此操作的最佳方法是什么?

回答by theJollySin

In Python, this is an easy exercise in using the datetimeformat strings:

在 Python 中,这是使用datetime格式字符串的简单练习:

from datetime import datetime

s = "8 March, 2017"
d = datetime.strptime(s, '%d %B, %Y')
print(d.strftime('%Y-%m-%d'))

See thistable for a full description of all the format qualifiers.

有关所有格式限定符的完整说明,请参阅表。

Here I use the datetime.strptimemethod to convert your datepicker.js string to a Python datetime object. And I use the .strftimemethod to print that object out as a string using the format you desire. At first those format strings are going to be hard to remember, but you can always look them up. And they well organized, in the end.

在这里,我使用datetime.strptime方法将 datepicker.js 字符串转换为 Python 日期时间对象。我使用该.strftime方法使用您想要的格式将该对象作为字符串打印出来。起初,这些格式字符串很难记住,但您可以随时查找它们。最后,他们组织得很好。

I do wonder, though: might it be better to stay in JavaScript than switch over to Python for this last step? Of course, if you are using Python elsewhere in your process, this is an easy solution.

不过,我确实想知道:在这最后一步中,留在 JavaScript 中是否比切换到 Python 更好?当然,如果您在流程的其他地方使用 Python,这是一个简单的解决方案。

回答by Bill Bell

Mark Reed's advice might be best in your case. One frequently overlooked alternative for dates is the arrowmodule, which offers some interesting features. In this case you can do:

Mark Reed 的建议可能最适合您的情况。一个经常被忽视的日期替代方案是箭头模块,它提供了一些有趣的功能。在这种情况下,您可以执行以下操作:

>>> import arrow
>>> arrow.get('8 March, 2017', 'D MMMM, YYYY').format('YYYY-MM-DD')
'2017-03-08'

As an example of a feature, if you capture that date you could format it in Russian.

作为功​​能的示例,如果您捕获该日期,则可以将其格式化为俄语。

>>> aDate = arrow.get('8 March, 2017', 'D MMMM, YYYY')
>>> aDate.format('YYYY MMMM DD', locale='ru')
'2017 марта 08'