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 Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap