pythonlistdateformatreformatting

Reformat a list of dates from "/" to "-" (using python)


I have a list of dates.

['1/12/2022', '1/13/2022','1/17/2022']

How do I reformat them to look like this:

['2022-1-12', '2022-1-13','2022-1-17']

EDIT: My original post asked about the wrong format. I've corrected it because I meant for the the format to be "Year-Month-Day"


Solution

  • I am assuming you are using Python... Please correct me if I am wrong. You can loop through the list of dates using a enumerated for-loop (enumerate(list) function lets you know the index of each value during the loop) with each date, use the .replace() method of str to replace '/' with '-' like this:

    list_of_dates = ['1/12/2022', '1/13/2022','1/17/2022']
    for i, date in enumerate(list_of_dates):
        list_of_dates[i] = date.replace('/', '-')
    

    or use list comprehension like this (thank you @Eli Harold ):

    list_of_dates = [date.replace('/', '-') for date in list_of_dates]
    

    If you want to change the order of the numbers in the date string you can split them by the '/' or '-' into a new list and change the order if you want like this:

    for i, date in enumerate(list_of_dates):
        month, day, year = date.split('-') # assuming you already changed it to dashes
        list_of_dates[i] = f'{day}-{month}-{year}'