A-P*_*lgy 8 python global-variables strftime format-string
在我的应用程序中,我发现自己经常使用stftime,并且主要使用2种字符串格式 - ("%d /%m /%Y")和("%H:%M")
我不是每次都写字符串,而是希望将这些字符串存储在某些全局变量或其他内容中,因此我可以在我的应用中的一个位置定义格式字符串.
什么是pythonic方式呢?我应该使用全局字典,类,函数还是其他东西?
也许是这样的?
class TimeFormats():
def __init__(self):
self.date = "%d/%m/%Y"
self.time = "%H:%M"
Run Code Online (Sandbox Code Playgroud)
或者像这样?
def hourFormat(item):
return item.strftime("%H:%M")
Run Code Online (Sandbox Code Playgroud)
谢谢您的帮助
你可以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()))
Run Code Online (Sandbox Code Playgroud)
结果:
18/01/2017
10:38
Run Code Online (Sandbox Code Playgroud)
你只需要将time结构传递给新函数.该函数保存格式.
注意:您也可以这样做lambda:
time_dhm = lambda t : time.strftime("%d/%m/%Y",t)
Run Code Online (Sandbox Code Playgroud)
您可以创建自己的设置模块,就像 django 一样。
设置.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)
Run Code Online (Sandbox Code Playgroud)
别处
from settings import DATE_FORMAT
...
time.strftime( DATE_FORMAT, ...)
Run Code Online (Sandbox Code Playgroud)
或者
import settings
...
time.strftime( settings.DATE_FORMAT, ...)
Run Code Online (Sandbox Code Playgroud)