As you can see in my comment, you just need to use the right matching mask to get it right.
Your date strings are in the format %b %d, %Y
, so you need to use the same mask in strptime()
. With that in mind, a function like this will do the job:
from datetime import datetime
def mdy_to_ymd(d):
return datetime.strptime(d, '%b %d, %Y').strftime('%Y-%m-%d')
And here is a proof of concept:
>>> from datetime import datetime
>>>
>>>
>>> def mdy_to_ymd(d):
... return datetime.strptime(d, '%b %d, %Y').strftime('%Y-%m-%d')
...
>>> mdy_to_ymd('Jan 25, 2021')
'2021-01-25'
>>>
Bear in mind that strptime()
creates a datetime
object from a string
matching a date using masking characters format. Once you get the right mask and the right representation in a datetime
object, you can convert it to the desired format using strftime()
.
For more information, check strftime()
and strptime()
Format Codes.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…