Convert datetime object to date string in Python?

How can I convert a datetime object to a string of date only in Python?

I have a datetime object like datetime.datetime(2012, 2, 23, 0, 0) and I want to convert it to a string like '2/23/2012'. How can I achieve this in python date to string format?

Hello @sakshikuchroo

I recommend using the strftime() method for converting a datetime object to a string in Python. It’s one of the most flexible and commonly used approaches. You can specify the exact format you need for the date, which gives you full control over how it appears. Here’s an example:

import datetime

dt = datetime.datetime(2012, 2, 23, 0, 0)
date_string = dt.strftime('%m/%d/%Y')
print(date_string)  # Output: '02/23/2012'

In this example, the strftime('%m/%d/%Y') format string ensures the date is output as MM/DD/YYYY. You can easily adjust the format to your needs!

Let me know if you have any further Doubts.

Hello All!

That’s a good approach! But, if you’re only interested in the date and not the time part, you can extract the date first using the date() method, and then use strftime() for formatting. This method ensures that only the date (no time) is included in your output. Here’s how:

import datetime

dt = datetime.datetime(2012, 2, 23, 0, 0)
date_string = dt.date().strftime('%m/%d/%Y')
print(date_string)  # Output: '02/23/2012'

This way, you’re making sure you’re working with just the date, not the full datetime object. It could be useful for cases where the time isn’t necessary.

Thank you!

Great points from both of you! If you’re looking for a simpler, quicker approach and don’t mind sacrificing some flexibility, you can use Python’s f-string or the format() method to manually access the month, day, and year components. Here’s a straightforward example:

import datetime

dt = datetime.datetime(2012, 2, 23, 0, 0)
date_string = f'{dt.month}/{dt.day}/{dt.year}'
print(date_string)  # Output: '2/23/2012'

This method is less flexible than strftime(), but it works well for simpler tasks where you only need basic formatting. It’s quick, especially when you don’t require special date formats.