如何获取datetime.strftime的最大长度?
我现在正在做一个命令行程序,在里面我需要打印日期。
我使用的是 datetime.datetime.strftime
这个方法:
import datetime
d = datetime.datetime(2012,12,12)
date_str = d.strftime(config.output_str)
这里的 config.output_str
是一个格式字符串,用户可以自己设置。
有没有办法知道字符串 date_str
最大会有多长呢?
特别是当使用像 u'%d %B %Y'
这样的格式字符串时,月份的长度(%B
)会根据用户的语言而变化。
2 个回答
0
这是我为了解决这个问题而写的方案,供有兴趣的人参考。
我使用给定的格式字符串 format_str
来判断它可能有多长。因此,我假设只有月份和日期的长度会有所不同。
这个函数会遍历所有的月份,找出哪个月份的名称最长,然后再用之前找到的最长月份去遍历日期。
import datetime
def max_date_len(format_str):
def date_len(date):
return len(date.strftime(format_str))
def find_max_index(lst):
return max(range(len(lst)), key=lst.__getitem__)
# run through all month and add 1 to the index since we need a month
# between 1 and 12
max_month = 1 + find_max_index([date_len(datetime.datetime(2012, month, 12, 12, 12)) for month in range(1, 13)])
# run throw all days of the week from day 10 to 16 since
# this covers all weekdays and double digit days
return max([date_len(datetime.datetime(2012, max_month, day, 12, 12)) for day in range(10, 17)])
4
如果你没有使用 locale
模块来设置地区,那么 Python 就会使用 C 地区,这样你就可以预测输出的最大长度。所有的字符串都会是英文的,而且每种格式字符的最大长度都是已知的。
你可以自己解析这个字符串,数一数非格式字符的数量,然后把格式字符映射到该字段的最大长度。
如果你使用了 locale
,那么你就需要根据不同语言来计算最大长度。你可以通过循环遍历月份、星期几和上午/下午来自动处理这些依赖地区的字段,并测量 %a
、%A
、%b
、%B
、%c
、%p
、%x
和 %X
格式的最大长度。我建议在需要的时候动态计算。
其他格式的最大长度是固定的,不会因为地区而变化,并且都有文档记录的最大长度(在 strptime
表格 中的例子是典型的,你可以依赖这些文档来了解字段长度)。