This is 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 strit will still output a readable string:
>>> str(ts)
'1895-10-06 16:04:05'
edit
The closest way to emulate the default behavior is to hardcode the dictionary, for example:
>>> d = {'%Y': '{0.year}', '%m': '{0.month:02}'}
>>> '{%Y}-{%m}'.format(**d).format(ts)
'1895-10'
You will need to enclose all formatting specifiers in curly braces with a simple regular expression:
>>> re.sub('(%\w)', r'{\1}', '%Y-%m-%d %H sdf')
'{%Y}-{%m}-{%d} {%H} sdf'
and in the end we come to a 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 table.
2
: : %Y, %m, %d, %H, %M, %S, %f, , , , babel .