How to Change a Date Format in Python?

Last updated on December 28, 2022 by Ayaz Ali Shah

In this article, we will learn to change the format of a given date in python. The datetime class accepts three parameters. First is the year, second is the month and third is the day. So let’s get started.

First, we need to import datetime module and datetime class

from datetime import datetime

Next, pass the date into the datetime class that creates the datetime object.

# create datetime object of provided date
datetimeObject = datetime(2022,6,30)
print('datetimeObject:', datetimeObject.strftime('%d-%B-%Y'))
# Output: datetimeObject: 30-June-2022

We assigned a datetime object to the datetimeObject variable that can access strftime() function that returns the date in a string with the desired format.

In the strftime() function, we passed three directives as an argument to show the date. Following are the meaning of each directive

  • %d: returns the day of month 01 to 31
  • %B: returns the full name of Month
  • %Y: returns year in four-digit, for example, 2022


Share on:

Related Posts

Tags: Date, Python,