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
JavaScript
x
4
1
today = date.today().strftime('%d/%m/%y')
2
3
print(type(today))
4
Advertisement
Answer
This is the right way to achieve your goal:
JavaScript
1
8
1
from datetime import date
2
3
today = date.today()
4
today_string = today.strftime('%d/%m/%Y')
5
6
print(type(today))
7
print(today_string)
8
Output:
JavaScript
1
3
1
<class 'datetime.date'>
2
26/10/2022
3
To change the date
class default format:
mydatetime.py
JavaScript
1
14
14
1
from datetime import datetime as system_datetime, date as system_date
2
3
4
class date(system_date):
5
def __str__(self):. # similarly for __repr__
6
return "%02d-%02d-%02d" % (self._day, self._month, self._year)
7
8
class datetime(system_datetime):
9
def __str__(self):. # similarly for __repr__
10
return "%02d-%02d-%02d" % (self._day, self._month, self._year)
11
12
def date(self):
13
return date(self.year, self.month, self.day)
14
Read More: How to globally change the default date format in Python