编写自定义字符串格式化程序

时间:2019-05-30 19:47:52

标签: python string string-formatting formatter

我正在为我的文化编写一个日期时间包,并且我需要字符串格式功能,例如日期时间包中的strptime,strftime。

我在下面编写了代码,效果很好。但这并没有让我感觉很好。

我不喜欢使用format

如果有其他方法,感谢与我分享。

_replaces = {
    "%y": "{year:y}",
    "%m": "{month:m}",
    "%n": "{month_name:n}",
    "%d": "{day:d}",
    "%h": "{hour:h}",
    "%M": "{minute:M}",
    "%s": "{second:s}",
}

_month_names = [
    ...
]

class _TimeFormatter(string.Formatter):
    def format_field(self, value, spec):
        value = cgi.escape(value)
        spec = spec[:-1] + 's'
        return super(_TimeFormatter, self).format_field(value, spec)


def _do_replace(format):
    for k, v in _replaces.items():
        format = format.replace(k, v)
    return format


def fmt(date_time, format="%y/%m/%d %h:%M:%s"):
    format = _do_replace(format)
    jd = ...
    date = ...
    date_dict = {
        "year": date[0],
        "month": date[1],
        "month_name": _month_names[int(date[1])],
        "day": date[2],
        "hour": str(date_time.hour),
        "minute": str(date_time.minute),
        "second": str(date_time.second),
    }
    return _TimeFormatter().format(format, **date_dict)

# example = fmt(
#   datetime.datetime(2019, 5, 28, 1, 10, 33),
#   "%h:%M:%s %d/%m/%y"
#)
# output: "1:10:33 7/3/1398"

0 个答案:

没有答案
相关问题