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"
CodePudding user response:
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}'
CodePudding user response:
you can use strptime
from datetime import datetime
dates = []
for date_str in ['1/12/2022', '1/13/2022','1/17/2022']:
date = datetime.strptime(date_str, '%m/%d/%Y')
dates.append(date.strftime('%m-%d-%Y'))
CodePudding user response:
I opted to split the individual dates and then add in the "-" delimiter after the fact, but you could also replace those on iteration. Once your data has been transformed, I just pushed it into a new list of reformatted dates.
This may not result in the best performance for longer iterations, though.
dates = ['1/12/2022', '1/13/2022','1/17/2022']
newdates = []
for x in range(0, len(dates)):
split_date = dates[x].split('/')
month = split_date[0]
day = split_date[1]
year = split_date[2]
your_date = year "-" month "-" day
newdates.apppend(your_date)
print(your_date)
And the output:
2022-1-12
2022-1-13
2022-1-17
CodePudding user response:
from datetime import datetime
dates = [datetime.strptime(x, "%-m/%-d/%Y") for x in list_of_dates]
new_dates = [x.strftime("%Y-%-m-%-d") for x in dates]
CodePudding user response:
dates = ['1/12/2022', '1/13/2022','1/17/2022']
dates = [x.replace('/', '-') for x in dates]
