简体   繁体   中英

How to globally change the default date format in Python

I'm coding a Python script, in which I currently use strftime when I want to display a date according to a specific format. However, the format I use is consistently always the same throughout the script, thus it feels a waste of time and a violation of the DRY principle having to explicitly call strftime(myFormat) in every print .

I'm looking for a way to define only once what the date string format used in the script is, for all strings.

I tried this:

from datetime import datetime

def format_string(self):
    return "%02d-%02d-%02d" % (self._day, self._month, self._year)
datetime.date.__str__ = format_string

which doesn't work because __str__ is read-only.

Say __str__ was not readonly, how would your solution work when importing datetime in all modules? You would have to define the __str__ in the beginning of each module.

To resolve that, you will probably create a base module, say "mydatetime.py", define __str__ in that module, and then do from mydatetime import datetime in all modules where you"ll print

So if we are going to have our own base module, why not just create our own class

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)

and then you can replace all from datetime import datetime with from mydatetime import datetime

You could define a method pretty_format_date() that you import across your codebase, and that method would contain the strftime(myFormat) to be reused.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM