Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String with month name to datetime

Tags:

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?

like image 211
Arjun Avatar asked Mar 23 '17 15:03

Arjun


People also ask

How do I convert a string to a datetime in Python?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

How do you get month from string in Python?

Method #1 : Using strftime() + %B In this, we use strftime() which converts date object to a string using a format, and by providing %B, it's enforced to just return a Month Name.

How do I change the month format in Python?

strftime() Date Format Codes The same set of directives are shared between both the strptime() and strftime() methods. %d : Returns the day of the month, from 1 to 31. %m : Returns the month of the year, from 1 to 12. %Y : Returns the year in four-digit format (Year with century).

How do you convert date to month and year in Python?

In this article, we are going to convert DateTime string of the format 'yyyy-mm-dd' into DateTime using Python. yyyy-mm-dd stands for year-month-day . We can convert string format to datetime by using the strptime() function. We will use the '%Y/%m/%d' format to get the string to datetime.


1 Answers

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.

like image 89
john_science Avatar answered Oct 19 '22 18:10

john_science