Skip to content

Instantly share code, notes, and snippets.

@kbourgoin
Last active May 30, 2017 21:09
Show Gist options
  • Save kbourgoin/be5dbb808c6f854236ecb273e9453e3f to your computer and use it in GitHub Desktop.
Save kbourgoin/be5dbb808c6f854236ecb273e9453e3f to your computer and use it in GitHub Desktop.
import calendar
import datetime
import time
import timeit
def toInternal(dt):
if dt is not None:
seconds = calendar.timegm(dt.utctimetuple())
# Avoiding the invalid range of years (100-1899) for mktime in Python < 3
if dt.year not in range(100, 1900):
seconds = (calendar.timegm(dt.utctimetuple()) if dt.tzinfo
else time.mktime(dt.timetuple()))
return int(seconds) * 1000000 + dt.microsecond
def toInternal2(dt):
if dt is not None:
try:
seconds = (calendar.timegm(dt.utctimetuple()) if dt.tzinfo
else time.mktime(dt.timetuple()))
except ValueError:
seconds = calendar.timegm(dt.utctimetuple())
return int(seconds) * 1000000 + dt.microsecond
def main():
print('\n\nTiming of naive datetimes before 1800')
print('------------------------------')
print('Without try/except: {}s'.format(
timeit.timeit('toInternal(dt)',
setup='from __main__ import toInternal; import datetime; dt = datetime.datetime(1600,1,1)')))
)))
print('With try/except: {}s'.format(
timeit.timeit('toInternal2(dt)',
setup='from __main__ import toInternal2; import datetime; dt = datetime.datetime(1600,1,1)')))
print('\n\nTiming of naive datetimes after 1800')
print('------------------------------')
print('Without try/except: {}s'.format(
timeit.timeit('toInternal(dt)',
setup='from __main__ import toInternal; import datetime; dt = datetime.datetime(1900,1,1)')))
print('With try/except: {}s'.format(
timeit.timeit('toInternal2(dt)',
setup='from __main__ import toInternal2; import datetime; dt = datetime.datetime(1900,1,1)')))
print('\n\nTiming of tz-aware datetimes before 1800')
print('------------------------------')
print('Without try/except: {}s'.format(
timeit.timeit('toInternal(dt)',
setup='from __main__ import toInternal; import pytz; import datetime; dt = datetime.datetime(1600,1,1, tzinfo=pytz.utc)')))
print('With try/except: {}s'.format(
timeit.timeit('toInternal2(dt)',
setup='from __main__ import toInternal2; import pytz; import datetime; dt = datetime.datetime(1600,1,1, tzinfo=pytz.utc)')))
print('\n\nTiming of datetimes after 1800')
print('------------------------------')
print('Without try/except: {}s'.format(
timeit.timeit('toInternal(dt)',
setup='from __main__ import toInternal; import pytz; import datetime; dt = datetime.datetime(1900,1,1, tzinfo=pytz.utc)')))
print('With try/except: {}s'.format(
timeit.timeit('toInternal2(dt)',
setup='from __main__ import toInternal2; import pytz; import datetime; dt = datetime.datetime(1900,1,1, tzinfo=pytz.utc)')))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment