1👍
✅
You can use dateutil
by installing pip install python-dateutil
Then
>>>from dateutil import parser
>>>mydate = "June 3, 2001"
>>>str(parser.parse(mydate).date())
'2001-06-03'
1👍
You can use datetime.strptime , if you are using python –
from datetime import datetime
d = datetime.datetime.strptime("June 3 , 2001" , "%B %d , %Y")
d
>> datetime.datetime(2001, 6, 3, 0, 0)
Please understand that %B
(notice capital B) -> stands for complete month names (like January / February / June)
If you would be using the 3 letter abbreviations instead (like Jan / Feb / Jun) , use %b
.
To get back the date in the format you ask for use datetime.strftime
, like below –
d.strftime("%Y-%m-%d")
>> '2001-06-03'
If you have to use both formats for month names, You can first try using one format, and catch an exception, if that fails use the other format. Example –
from datetime import datetime
try:
d = datetime.datetime.strptime("June 3 , 2001" , "%B %d , %Y")
expect ValueError:
d = datetime.datetime.strptime("June 3 , 2001" , "%b %d , %Y")
d
>> datetime.datetime(2001, 6, 3, 0, 0)
Source:stackexchange.com