3
votes

I have strings like Jan 25, 2021 (Jan,Feb,Mar,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec) how can I convert it to 2021-01-25?

I was defining a function like:

def to_datetime(datestring):  
    
    #date = datetime.strptime(datestring, '%m.%d.%Y')
    #return date.strftime("%Y-%m-%d")
    
    return datetime.strptime(datestring, '%Y-%m-%d')

The issue are the month words so maybe I can replace the string to month number and then convert it but I am stuck

2
Did you try datetime.strptime('Jan 25, 2021', '%b %d, %Y').strftime('%Y-%m-%d')?accdias

2 Answers

6
votes

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.

-2
votes

you can use

date_like_you_dont_want = "Jan 2,2021".lower()

day = date_like_you_dont_want[4:6]

if not ',' in day:
    year = date_like_you_dont_want[7:]
else:
    day=date_like_you_dont_want[4]
    year=date_like_you_dont_want[6:]

month=date_like_you_dont_want[:3]
if month =='jan':
    month = '01'
elif month =='fev':
    month = '02'
elif month =='mar':
    month = '03'
elif month =='may':
    month = '04'
elif month =='apr':
    month = '05'
elif month =='jun':
    month = '06'
elif month =='jul':
    month = '07'
elif month =='aug':
    month = '08'
elif month =='sep':
    month = '09'
elif month =='oct':
    month = '10'
elif month =='mov':
    month = '11'
elif month =='dez':
    month = '12'

print(year+'-'+day+'-'+month)