Home > Software engineering >  How to change Day/Month/Year format to Month/Day/Year in Python
How to change Day/Month/Year format to Month/Day/Year in Python

Time:03-19

I have a column that the date is in Day/Month/Year format and it is stored in object format. How can I change it to Month/Day/Year format in python?

Here is an example: How can I change 13/3/2021 to 3/13/2021?

CodePudding user response:

Simple solution is using split:

def convert_format1(s: str):
    d, m, y = s.split("/")
    return "/".join((m, d, y))

Or you can use datetime module to convert string to datetime object(.strptime) and vice versa(.strftime):

from datetime import datetime

def convert_format2(s: str):
    source_format = "%d/%m/%Y"
    destination_format = "%m/%d/%Y"
    d = datetime.strptime(s, source_format)
    return d.strftime(destination_format)

You can then apply these functions to your dataframe's column.

note: AFAIK .strftime() method adds zero padding to the string representation of day and month. If you don't want this behavior you have to strip it manually after that.

note: second function is safer since it checks the dates to be valid as well.

CodePudding user response:

import datetime
t = datetime.date.today()
print(t.month,t.day,t.year,sep="/")

change the value inside the print should let you set yourself

  • Related