在1900年之前的Python中格式化日期字符串? [英] Formatting date string in Python for dates prior to 1900?

查看:176
本文介绍了在1900年之前的Python中格式化日期字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释在Python中格式化日期时间字符串的最佳方法,其中日期值在1900年之前? strftime 需要晚于1900年的日期。

Can anyone explain the best way to format a date time string in Python where the date value is prior to the year 1900? strftime requires dates later than 1900.

推荐答案

这有点麻烦,但它起作用(至少在python的稳定版本中):

It's a bit cumbersome, but it works (at least in stable versions of python):

>>> ts = datetime.datetime(1895, 10, 6, 16, 4, 5)
>>> '{0.year}-{0.month:{1}}-{0.day:{1}} {0.hour:{1}}:{0.minute:{1}}'.format(ts, '02')
'1895-10-06 16:04'

注意 str 仍然会产生一个可读的字符串:

note that str would still produce a readable string:

>>> str(ts)
'1895-10-06 16:04:05'

编辑

模拟默认行为的最接近的方式是对字典进行硬编码,例如:

edit
The closest possible way to emulate the default behaviour is to hard-code the dictionary such as:

>>> d = {'%Y': '{0.year}', '%m': '{0.month:02}'}    # need to include all the formats
>>> '{%Y}-{%m}'.format(**d).format(ts)
'1895-10'

您需要使用简单的正则表达式将所有格式说明符括入大括号中:

You'll need to enclose all format specifiers into the curly braces with the simple regex:

>>> re.sub('(%\w)', r'{\1}', '%Y-%m-%d %H sdf')
'{%Y}-{%m}-{%d} {%H} sdf'

最后我们来看简单的代码:

and at the end we come to simple code:

def ancient_fmt(ts, fmt):
    fmt = fmt.replace('%%', '%')
    fmt = re.sub('(%\w)', r'{\1}', fmt)
    return fmt.format(**d).format(ts)

def main(ts, format):
    if ts.year < 1900:
        return ancient_format(ts, fmt)
    else:
        return ts.strftime(fmt)

其中 d 是一个全局字典,其中与 strftime

where d is a global dictionary with keys corresponding to some specifiers in strftime table.

编辑2

要澄清:此方法仅适用于以下说明符:%Y,%m,%d,%H,% M,%S,%f ,即那些是数字的,如果您需要文本信息,最好使用babel或任何其他解决方案。

edit 2
To clarify: this approach will work only for the following specifiers: %Y, %m, %d, %H, %M, %S, %f, i.e., those that are numeric, if you need textual information, you'd better off with babel or any other solution.

这篇关于在1900年之前的Python中格式化日期字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆