Formatting date string in Python for dates prior to 1900?

后端 未结 4 1830
梦谈多话
梦谈多话 2020-12-21 07:00

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.<

4条回答
  •  臣服心动
    2020-12-21 07:09

    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'
    

    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)
    

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

    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.

提交回复
热议问题