如何在Python中格式化1900年前的日期字符串?

3 投票
4 回答
3762 浏览
提问于 2025-04-15 14:51

有没有人能解释一下,在Python中如何格式化一个日期时间字符串,特别是当日期早于1900年时?因为strftime这个方法只支持1900年以后的日期。

4 个回答

1

日历在每400年里是完全一样的。所以,只需要在调用 datetime.strftime() 之前,把年份改成400的倍数,比如 year >= 1900 就可以了。

下面的代码展示了这种方法可能会遇到的问题:

#/usr/bin/env python2.6
import re
import warnings
from datetime import datetime


def strftime(datetime_, format, force=False):
    """`strftime()` that works for year < 1900.

    Disregard calendars shifts.

    >>> def f(fmt, force=False):
    ...     return strftime(datetime(1895, 10, 6, 11, 1, 2), fmt, force)
    >>> f('abc %Y %m %D') 
    'abc 1895 10 10/06/95'
    >>> f('%X')
    '11:01:02'
    >>> f('%c') #doctest:+NORMALIZE_WHITESPACE
    Traceback (most recent call last):
    ValueError: '%c', '%x' produce unreliable results for year < 1900
    use force=True to override
    >>> f('%c', force=True)
    'Sun Oct  6 11:01:02 1895'
    >>> f('%x') #doctest:+NORMALIZE_WHITESPACE
    Traceback (most recent call last):
    ValueError: '%c', '%x' produce unreliable results for year < 1900
    use force=True to override
    >>> f('%x', force=True)
    '10/06/95'
    >>> f('%%x %%Y %Y')
    '%x %Y 1895'
    """
    year = datetime_.year
    if year >= 1900:
       return datetime_.strftime(format)

    # make year larger then 1900 using 400 increment
    assert year < 1900
    factor = (1900 - year - 1) // 400 + 1
    future_year = year + factor * 400
    assert future_year > 1900

    format = Specifier('%Y').replace_in(format, year)
    result = datetime_.replace(year=future_year).strftime(format)
    if any(f.ispresent_in(format) for f in map(Specifier, ['%c', '%x'])):
        msg = "'%c', '%x' produce unreliable results for year < 1900"
        if not force:
            raise ValueError(msg + " use force=True to override")
        warnings.warn(msg)
        result = result.replace(str(future_year), str(year))
    assert (future_year % 100) == (year % 100) # last two digits are the same
    return result


class Specifier(str):
    """Model %Y and such in `strftime`'s format string."""
    def __new__(cls, *args):
        self = super(Specifier, cls).__new__(cls, *args)
        assert self.startswith('%')
        assert len(self) == 2
        self._regex = re.compile(r'(%*{0})'.format(str(self)))
        return self

    def ispresent_in(self, format):
        m = self._regex.search(format)
        return m and m.group(1).count('%') & 1 # odd number of '%'

    def replace_in(self, format, by):
        def repl(m):
            n = m.group(1).count('%')
            if n & 1: # odd number of '%'
                prefix = '%'*(n-1) if n > 0 else ''
                return prefix + str(by) # replace format
            else:
                return m.group(0) # leave unchanged
        return self._regex.sub(repl, format)


if __name__=="__main__":
    import doctest; doctest.testmod()
1

babel这个国际化库似乎没有遇到什么问题。你可以查看它的文档,了解babel.dates的相关内容。

4

这有点麻烦,但它确实有效(至少在稳定版本的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 仍然会生成一个可读的字符串:

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

编辑
要模拟默认行为,最接近的方法是硬编码一个字典,比如:

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

你需要把所有的格式说明符放在大括号里,并用简单的正则表达式处理:

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

最后我们得到了简单的代码:

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中的说明符。

编辑 2
为了澄清:这种方法只适用于以下说明符:%Y, %m, %d, %H, %M, %S, %f,也就是说,这些都是数字类型的。如果你需要文本信息,最好使用babel或其他解决方案。

撰写回答