Convert a datetime.date() object with underscores rather than hyphens

I’m trying to create a datetime.date object, but change the hyphens in the date to underscores. Is there a way to do this with datetime.date objects? Or would I have to somehow do this with the datetime object?

from datetime import datetime


date = datetime.strptime('2021-12-30', '%Y-%m-%d').date()

print(type(date))
# <class 'datetime.date'>
print(date)
# 2021-12-30

date_2 = date.strftime('%Y_%m_%d')
print(date_2)
# 2021_12_30
print(type(date_2))
# <class 'str'> I want this to stay as a datetime.date object

>Solution :

The datetime object you’re referring to only exists in this shape: datetime.date(2021, 12, 30). When you call print() on it, it simply turns it into a string and prints it:

> print(date)
2021-12-30

Which is to say, you cannot have underscores instead of dashes unless you decide to work with a strings. strftime() is a great way of transforming the date into a string. Otherwise you can use the following for the same effect:

> str(date).replace('-', '_')
2021_12_30

For more colour on Python strings and date objects, check out this answer: How to print a date in a regular format?

Leave a Reply