1

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
M. Phys
  • 139
  • 15

2 Answers2

1

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?

vtasca
  • 1,660
  • 11
  • 17
0

print(date) in the first example is string representation of python datetime object handled by datetime.str method

date.strftime is function for getting the string representation according to the given format

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 25 '22 at 15:23