jon
jon

Reputation: 359

How to rearrange the order of a DateTime object

I have a list of dates DOB as strings in the format YYYY-MM-DD and I need to convert it to MM/DD/YYYY. I'm not particularly picky if it is a string or a DateTime object, I just need the order switched. I have the following code that does do that, but I'm wondering if there is a simpler or more pythonic way of doing this.

for date in DOB:
    new_date = datetime.strptime(date,"%Y-%m-%d").date()
    new_date_format.append(f"{new_date.month}/{new_date.day}/{new_date.year}")

Also, I'm looking to do this in native python, not, for example, pandas.

Upvotes: 1

Views: 1597

Answers (1)

Bruno Mello
Bruno Mello

Reputation: 4618

I think this is what you want:

for date in DOB:
    new_date = datetime.strptime(date,"%Y-%m-%d").strftime("%m/%d/%Y")
    new_date_format.append(new_date)

Upvotes: 3

Related Questions