Convert a object with underscores rather than hyphens

I’m trying to create a object, but change the hyphens in the date to underscores. Is there a way to do this with 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()

# <class ''>
# 2021-12-30

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

>Solution :

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

> print(date)

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('-', '_')

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