From $PYTHONHOME/lib/python2.7/calendar.py, timegm is defined as
EPOCH = 1970
_EPOCH_ORD = datetime.date(EPOCH, 1, 1).toordinal()
def timegm(tuple):
"""Unrelated but handy function to calculate Unix timestamp from GMT."""
year, month, day, hour, minute, second = tuple[:6]
days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1
hours = days*24 + hour
minutes = hours*60 + minute
seconds = minutes*60 + second
return seconds
Is there any reason why days is not calculated as :
days = datetime.date(year, month, day).toordinal() - _EPOCH_ORD
Can anyone think of cases where the previous expression would break?
“range checks” that the
day(combined with year and month) is part of a validdatetime.date.datetime.date(year, month, 1)does not — or rather, only requires thatyearandmonthare valid.Apparently some user was exploiting this “feature” (of not checking the day) and for the sake of backwards compatibility (with Python2.2!) the developers kept this behavior. See Raymond Hettinger’s comment in commit #27881.
PS. You can find the commit that changed this line in
calendar.pyby running(provided you’ve
hg cloned the CPython repository).Then, to find more about commit #27881, you can search http://hg.python.org/