In my app I find myself using stftime a lot, and mostly with 2 strings formats - ("%d/%m/%Y") and ("%H:%M")
Instead of writing the string each time, I want to store those strings in some global var or something, so I can define the format strings in just one place in my app.
What is the pythonic way of doing that? Should I use a global dict, a class, a function, or maybe something else?
Maybe like this?
class TimeFormats():
def __init__(self):
self.date = "%d/%m/%Y"
self.time = "%H:%M"
Or like this?
def hourFormat(item):
return item.strftime("%H:%M")
Thanks for the help
You could create your own settings module, like django does.
settings.py:
# locally customisable values go in here
DATE_FORMAT = "%d/%m/%Y"
TIME_FORMAT = "%H:%M"
# etc.
# note this is Python code, so it's possible to derive default values by
# interrogating the external system, rather than just assigning names to constants.
# you can also define short helper functions in here, though some would
# insist that they should go in a separate my_utilities.py module.
# from moinuddin's answer
def datetime_to_str(datetime_obj):
return datetime_obj.strftime(DATE_FORMAT)
elsewhere
from settings import DATE_FORMAT
...
time.strftime( DATE_FORMAT, ...)
or
import settings
...
time.strftime( settings.DATE_FORMAT, ...)