Reputation: 5954
I know there are similar questions out there, but most simply convert the alphanumerical date string to a datetime
object with the strptime
method, which is not what I'm going for. All I'm trying to do is convert string like so.
Format of Possible Input
December 7, 2015
October 24, 2018
Desired Output
2015-12-07
2018-10-24
How I've Gone About It
""" funding_expiration[0] is equal to strings like 'December 7, 2015' """
funding_expiration = funding_expiration[0].text.split()
""" still need to convert Month (%B) to ## (%m) """
funding_expiration[1] = funding_expiration[1].replace(',', '')
# add padding to single digit days
if len(funding_expiration[1]) is 1:
funding_expiration[1] = funding_expiration[1].zfill(1)
# format numerical date string
funding_expiration = funding_expiration[2] + '-' + funding_expiration[0] + '-' + funding_expiration[1]
I'm still trying to figure out an efficient way to convert the full name of months into their corresponding numerals. I'm new to Python, so I'm wondering whether or not there's a more efficient way to accomplish this?
Upvotes: 0
Views: 85
Reputation: 51345
datetime.strptime
can work in your case too. You can use the %B
directive to parse full month names.
import datetime
s = 'December 7, 2015'
date_string = str(datetime.datetime.strptime(s, '%B %d, %Y').date())
>>> date_string
'2015-12-07'
Upvotes: 1
Reputation: 164693
Here's a solution using 3rd party dateutil
:
from dateutil import parser
L = ['December 7, 2015', 'October 24, 2018']
res_str = [parser.parse(x).strftime('%Y-%m-%d') for x in L]
['2015-12-07', '2018-10-24']
Upvotes: 1