将带有月份名称的字符串转换为日期时间 [英] Convert String with month name to datetime

查看:304
本文介绍了将带有月份名称的字符串转换为日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 pickadate.js ,它以以下格式返回日期:

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

8 March, 2017

我想将其转换为 datetime 格式:

yyyy-mm-dd

用Python做到这一点的最佳方法是什么?

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

推荐答案

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

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

from datetime import datetime

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

请参见表以获取所有格式限定符的完整说明。

See this table for a full description of all the format qualifiers.

在这里,我使用 datetime.strptime 方法将datepicker.js字符串转换为Python datetime对象。然后,我使用 .strftime 方法以所需的格式将对象打印为字符串。最初,这些格式字符串将很难记住,但是您始终可以查找它们。最终,他们井井有条。

Here I use the datetime.strptime method to convert your datepicker.js string to a Python datetime object. And I use the .strftime method 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.

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

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.

这篇关于将带有月份名称的字符串转换为日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆