DuckyGoGo
DuckyGoGo

Reputation: 35

Converting from dd mm yyyy to mm/dd/yyyy in Python

I have a list which contains some dates:

['1 Jan 2019', '5 Feb 2019', '6 Feb 2019', '19 Apr 2019', '1 May 2019', 
'19 May 2019', '5 Jun 2019', '9 Aug 2019', '11 Aug 2019', '27 Oct 2019', 
'25 Dec 2019']

I would like to use a for loop to covert each item in the list to the following format, mm/dd/yyyy, for example, from 5 Feb 2019 to 02/31/2019).

Upvotes: 1

Views: 532

Answers (1)

hkr
hkr

Reputation: 270

Maybe something like this?

from datetime import datetime
dates = ['1 Jan 2019', '5 Feb 2019', '6 Feb 2019', '19 Apr 2019', '1 May 2019', 
'19 May 2019', '5 Jun 2019', '9 Aug 2019', '11 Aug 2019', '27 Oct 2019', '25 Dec 2019']

new_dates = [datetime.strptime(date, '%d %b %Y').strftime("%m/%d/%Y") for date in dates]

new_dates will look like:

['01/01/2019', '02/05/2019', '02/06/2019', '04/19/2019', '05/01/2019', '05/19/2019', '06/05/2019', '08/09/2019', '08/11/2019', '10/27/2019', '12/25/2019']

Documentation: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

Upvotes: 1

Related Questions