Home > Net >  Formatting todays date in python as date type
Formatting todays date in python as date type

Time:10-26

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))

CodePudding user response:

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 "d-d-d" % (self._day, self._month, self._year)

class datetime(system_datetime):
     def __str__(self):. # similarly for __repr__
           return "d-d-d" % (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

CodePudding user response:

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

  • Related