Created
August 1, 2013 23:40
-
-
Save gka/6136337 to your computer and use it in GitHub Desktop.
Python replacement for datetime.strftime that is able to handle dates before 1900. Written by Andrew Dalke on comp.lang.python (https://groups.google.com/forum/#!msg/comp.lang.python/v-9L1D6oc4k/3faS6YjTRg4J)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time, datetime | |
def _findall(text, substr): | |
# Also finds overlaps | |
sites = [] | |
i = 0 | |
while 1: | |
j = text.find(substr, i) | |
if j == -1: | |
break | |
sites.append(j) | |
i=j+1 | |
return sites | |
# I hope I did this math right. Every 28 years the | |
# calendar repeats, except through century leap years | |
# excepting the 400 year leap years. But only if | |
# you're using the Gregorian calendar. | |
def strftime(dt, fmt): | |
# WARNING: known bug with "%s", which is the number | |
# of seconds since the epoch. This is too harsh | |
# of a check. It should allow "%%s". | |
fmt = fmt.replace("%s", "s") | |
if dt.year > 1900: | |
return time.strftime(fmt, dt.timetuple()) | |
year = dt.year | |
# For every non-leap year century, advance by | |
# 6 years to get into the 28-year repeat cycle | |
delta = 2000 - year | |
off = 6*(delta // 100 + delta // 400) | |
year = year + off | |
# Move to around the year 2000 | |
year = year + ((2000 - year)//28)*28 | |
timetuple = dt.timetuple() | |
s1 = time.strftime(fmt, (year,) + timetuple[1:]) | |
sites1 = _findall(s1, str(year)) | |
s2 = time.strftime(fmt, (year+28,) + timetuple[1:]) | |
sites2 = _findall(s2, str(year+28)) | |
sites = [] | |
for site in sites1: | |
if site in sites2: | |
sites.append(site) | |
s = s1 | |
syear = "%4d" % (dt.year,) | |
for site in sites: | |
s = s[:site] + syear + s[site+4:] | |
return s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment