Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting date string in Python for dates prior to 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.

like image 658
Richard Avatar asked Dec 01 '25 19:12

Richard


1 Answers

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.

like image 83
SilentGhost Avatar answered Dec 04 '25 09:12

SilentGhost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!