How to change the format of date in Python

In this tutorial, we will see how we can change the format of data in Python in cool and easy ways.

I know you are here because you are stuck up with a problem to change the format of date in Python then this is the best place where you can find the best ways to solve the problem.

Come on let’s move ahead to find the awesome tricks to solve the problem.

To change the format of time and date in Python, firstly we must import the datetime module as shown below :

import datetime

After importing the Python datetime module we must give the input of time of date in any variable

Here I considered it as date_input and the input is given in the format YYYYMMDD

i.e date_input=YYYYMMDD

date_input = '20190707'
datetimeobject = datetime.strptime(date_input,'%Y%m%d')

Now we will convert the date_input into a new format. The new format of date must be saved in another variable say new_format.

The new format of date is DD-MM-YYYY

i.e new_format=DD-MM-YYYY

Here in the below piece of code strptime is a keyword which provides various functions of time and date

new_format = datetimeobject.strftime('%m-%d-%Y')
print(new_format)

OUTPUT:

07-07-2019

MM-DD-YYYY format

Now we will convert the date_input into another new format. This new format of date must be saved in another variable say new_format_1.

The new format of date is DD/MM/YYYY

i.e new_format_1=DD/MM/YYYY

new_format_1 = datetimeobject.strftime('%m/%d/%Y')
print (new_format_1)

OUTPUT:

07-07-2019

 

Do visit my another tutorial in Python

Leave a Reply

Your email address will not be published. Required fields are marked *