Where to hold common strftime strings like (“%d/%m/%Y”)

99封情书 提交于 2019-12-12 09:37:45

问题


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


回答1:


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



回答2:


you could use functools.partial to generate a function holding the format:

import time,functools

time_dhm = functools.partial(time.strftime,"%d/%m/%Y") 
time_hm = functools.partial(time.strftime,"%H:%M")

print(time_dhm(time.localtime()))
print(time_hm(time.localtime()))

result:

18/01/2017
10:38

you only have to pass the time structure to the new function. The function holds the format.

Note: you can do the same with lambda:

time_dhm = lambda t : time.strftime("%d/%m/%Y",t)



回答3:


I think it is better to create a custom function to achieve this. For example:

def datetime_to_str(datetime_obj):
    return datetime_obj.strftime("%d/%m/%Y")

Sample run:

>>> from datetime import datetime

>>> datetime_to_str(datetime(1990, 3, 12))
'12/03/1990'

It will be much more friendly for the fellow developers as the function name is self explanatory. Each time conversion of datetime to str is needed, they will know which function is needed to be called. And in case you want to change the format through out the application; there will be single point of change.



来源:https://stackoverflow.com/questions/41715751/where-to-hold-common-strftime-strings-like-d-m-y

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!