Formatting todays date in python as date type

Question:

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))
Asked By: tor daniel

||

Answers:

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

Answered By: Hamid Rasti

The default datetime simply outputs as is; but you can inherit and create a custom __repr__:

from datetime import datetime

class mydatetime(datetime):
    def __repr__(self):
        return self.strftime('%d/%m/%y')

mydatetime.today()

outputs 26/10/22

Answered By: Joost Döbken
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.