Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

python - Convert String with month name to datetime

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

8 March, 2017

I would like to convert this to the datetime format of:

yyyy-mm-dd

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...