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.



-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap