Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading