How to convert Python datetime object to a String

One of the most common operations one needs to do is converting datatime object to a str string object in Python.

To achieve this you need to make use of the strftime() method from datatime module.



Example:
import datetime

dt = datetime.datetime.now()
date_format = '%d-%m-%Y'
formatted_date = dt.strftime(date_format)

print(formatted_date)
Output:
04-07-2023

We have got the current date and time suing datetime.now() and converted it into date in dd-MM-yyyy date format.



Read More:

https://docs.python.org/2/library/time.html#time.strftime

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!