Change date format in Python

Introduction :

In Python, the date format can be changed using the ” datetime ” module.

  • The “datetime” module is a part of the standard library. It is powerful and flexible, making it easy to work with dates and times in Python.
  • “datetime” module provides classes for handling & working with dates and times.
  • It provides the classes like ‘datetime’, ‘date’, ‘time’ etc…

some of the key classes and  their functions :

  1. datetime.date: Represents a date (year, month, and day) without time.
  2.  datetime.time: Represents a time, independent of any particular day (hour, minute, second, microsecond).
  3. datetime.datetime: A combination of a date and a time, including year, month, day, hour, minute, second, and microsecond.
Examples :

Here are some of the examples of  changing date formats,

  1. ‘month Day, year’  to  DD-MM-YYYY
  2. MM/DD/YYYY  to  YYYY-DD-MM
  3. YYYY-DD-MM  to  DD/MM/YYYY, etc…

Steps  for writing a Python code for changing the date format:-

Step 1: –

For writing the code, firstly import the ‘datetime‘ module

syntax 

from datetime import datetime

 Step 2: –

Parse(divide) a date string into ‘datetime’ object by using “strptime(). ‘strptime’ string parse time. It is used to parse a string representing a date /time into the specified format.datetime.

syntax

datetime.strptime(date_string, format)

step 3:-

Format the ‘datetime’ object into a date string by using ” strftime() “. ‘strftime’ stands for “ string format time “. It is used to format a ‘datetime’ object into a string in a specified format.

syntax

datetime.strftime(format)

step 4:-

Print the output.

syntax

print(new date_str)

Program :

Now let’s write a program for an example which is mentioned above.

YYYY-DD-MM  to  DD/MM/YYYY

 

from datetime import datetime
 date_str = "2024-06-15" 
date_obj = datetime.strptime(date_str,"%Y-%m-%d")
 new_date_str = date_obj.strftime(%d/%m/%Y") 
print(new_date_str)
output:-
"15/06/2024"

In this Program, the date string “2024-06-15” is first parsed into a datetime object using strptime(), with the format “%Y-%m-%d”. Then, strftime() is used to format the datetime object into the new format “%d/%m/%Y”, resulting in “15/06/2024”.

Leave a Comment

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

Scroll to Top