Skip to content

Instantly share code, notes, and snippets.

@mitchellrj
Created March 8, 2012 12:42
Show Gist options
  • Save mitchellrj/2000837 to your computer and use it in GitHub Desktop.
Save mitchellrj/2000837 to your computer and use it in GitHub Desktop.
Python datetime.strftime < 1900 workaround
import datetime
import re
import warnings
def strftime(dt, fmt):
if dt.year < 1900:
# create a copy of this datetime, just in case, then set the year to
# something acceptable, then replace that year in the resulting string
tmp_dt = datetime.datetime(datetime.MAXYEAR, dt.month, dt.day,
dt.hour, dt.minute,
dt.second, dt.microsecond,
dt.tzinfo)
if re.search('(?<!%)((?:%%)*)(%y)', fmt):
warnings.warn("Using %y time format with year prior to 1900 "
"could produce unusual results!")
tmp_fmt = fmt
tmp_fmt = re.sub('(?<!%)((?:%%)*)(%y)', '\\1\x11\x11', tmp_fmt, re.U)
tmp_fmt = re.sub('(?<!%)((?:%%)*)(%Y)', '\\1\x12\x12\x12\x12', tmp_fmt, re.U)
tmp_fmt = tmp_fmt.replace(str(datetime.MAXYEAR), '\x13\x13\x13\x13')
tmp_fmt = tmp_fmt.replace(str(datetime.MAXYEAR)[-2:], '\x14\x14')
result = tmp_dt.strftime(tmp_fmt)
if '%c' in fmt:
# local datetime format - uses full year but hard for us to guess
# where.
result = result.replace(str(datetime.MAXYEAR), str(dt.year))
result = result.replace('\x11\x11', str(dt.year)[-2:])
result = result.replace('\x12\x12\x12\x12', str(dt.year))
result = result.replace('\x13\x13\x13\x13', str(datetime.MAXYEAR))
result = result.replace('\x14\x14', str(datetime.MAXYEAR)[-2:])
return result
else:
return dt.strftime(fmt)
@scottlawton
Copy link

Thanks for sharing some code ... though in this case I'm not sure it's correct. What cases did you test? e.g. for "%A" I get
1800-12-31 00:00:00 Friday
1801-01-01 00:00:00 Friday
... which shouldn't both be true. :-)

There's some useful test code on this version: http://code.activestate.com/recipes/306860-proleptic-gregorian-dates-and-strftime-before-1900/ ... let me know if you'd like my updated test script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment