在哪里保存常见的 strftime 字符串,如 ( "%d/%m/%Y" )



在我的应用程序中,我发现自己经常使用 stftime,并且主要使用 2 种字符串格式 - ("%d/%m/%Y") 和 ("%H:%M")

我想将这些字符串

存储在某个全局变量或其他东西中,而不是每次都编写字符串,这样我就可以在我的应用程序中的一个位置定义格式字符串。

这样做的pythonic方法是什么?我应该使用全局字典、类、函数还是其他东西?

也许像这样?

class TimeFormats():
    def __init__(self):
        self.date = "%d/%m/%Y"
        self.time = "%H:%M"

还是这样?

def hourFormat(item):
    return item.strftime("%H:%M")

感谢您的帮助

您可以使用functools.partial生成一个保存格式的函数:

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

结果:

18/01/2017
10:38

您只需将time结构传递给新函数。该函数保存格式。

注意:您可以对lambda执行相同的操作:

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

我认为最好创建一个自定义函数来实现这一点。例如:

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

示例运行:

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

对于其他开发人员来说,这将更加友好,因为函数名称是不言自明的。每次需要将datetime转换为str时,它们都会知道需要调用哪个函数。如果您想在整个应用程序中更改格式;将有单点变化。

你可以创建自己的设置模块,就像 django 一样。

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)

别处

from settings import DATE_FORMAT
...
time.strftime( DATE_FORMAT, ...)

import settings
...
time.strftime( settings.DATE_FORMAT, ...)

最新更新