How to Convert Date String to Different Format in Python?

Last updated on December 28, 2022

To change the date format we will need a datetime module, datetime class, strptime() function, and strftime() function. To begin with, let’s import the datetime module and datetime class.

from datetime import datetime

The from keyword imports datetime class from the datetime module.

Convert String to Date with Desire Format

In this case, we convert a string that contains a date into datetime. First, we need to convert the string into a datetime object. For converting a string into datetime we can use strptime(). The strptime() function creates a datetime object from the given string. It accepts two arguments; first date string and second date format.

# Create datetime object 
dateTimeObject = datetime.strptime('2022-06-25', '%Y-%m-%d')
print('date time object:  ', dateTimeObject.strftime('%d-%B-%Y'))
# Output: date time object:   25-June-2022

We used strptime() in this script to create a datetime object. For that, we passed two arguments into strptime() function in which the first is the date string and the second is the format of the date that the string contains. After creating a datetime object, we assigned it to the dateTimeObject variable.

Now, as we know, the variable dateTimeObject has a datetime object so it can access the strftime() function that represents the date in the string with the desired format. So in the strftime() function, we passed three directives as an argument to show the date. Following are the meaning of each directive

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

Conclusion

To convert a date string into a different format, first, you need to convert it into a datetime object through strptime() function. After creating a datetime object you can use strftime() function for changing the required date format.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: Date, Python, String,