I’m trying to get todays date in the format %d/%m/%y without converting to a string. I still want to have the date as the data type.
Following code returns an str
today = date.today().strftime('%d/%m/%y') print(type(today))
Advertisement
Answer
This is the right way to achieve your goal:
from datetime import date today = date.today() today_string = today.strftime('%d/%m/%Y') print(type(today)) print(today_string)
Output:
<class 'datetime.date'> 26/10/2022
To change the date
class default format:
mydatetime.py
from datetime import datetime as system_datetime, date as system_date class date(system_date): def __str__(self):. # similarly for __repr__ return "%02d-%02d-%02d" % (self._day, self._month, self._year) class datetime(system_datetime): def __str__(self):. # similarly for __repr__ return "%02d-%02d-%02d" % (self._day, self._month, self._year) def date(self): return date(self.year, self.month, self.day)
Read More: How to globally change the default date format in Python