This tutorial will teach how to represent date and time into various formats in Python using the strftime() function of a datetime module and time module.
The strftime() method returns a string representing of a datetime object according to the format codes.
Table of contents
How to Format Date and Time in Python
In Python, the date and time values are stored as datetime objects, but there are cases where we need to print the datetime objects into various string formats for better readability.
For example, you may need to represent a date numerically in format, like “17-06-2021“. On the other hand, you want to convert dates in textual string format like “Tuesday, 23 June 2021.”
The below steps show how to convert a datetime to string format using the strftime() function
- Import datetime module
Python’s datetime module provides functions that handle many complex functionalities involving the date and time. Import
datetimeclass using afrom datetime import datetimestatement. - Use strftime() function of a datetime class
Use
datetime.strftime(format)to convert adatetimeobject into a string as per the correspondingformat.
The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the%d-%m-%Y %H:%M:%Scodes convert date todd-mm-yyyy hh:mm:ssformat. - Use strftime() function of a time module
Use this step if you want to convert a
timeobject to string format. like, hours minutes seconds (hh:mm:ss). Use thetime.strptime(string[, format])function to convert atimeobject to a string format.