Search code examples
pythonstrftime

Is there a faster alternative to Python's strftime?


I'm processing hundreds of thousands of dates in Python and noticing that the strftime function is pretty slow.

I used timeit to check and it tells me that it takes roughly 0.004 which is fine for a small number but becomes problematic for processing a couple thousand for example.

print(min(timeit.Timer("now.strftime('%m/%d/%Y')", setup=setup).repeat(7,1000))

Is there any faster alternative?


Solution

  • Since you have a rigid format you can just access directly the fields of the datetime object and use Python string formatting to construct the required string:

    '{:02d}/{:02d}/{}'.format(now.month, now.day, now.year)
    

    In Python 3 this is about 4 times faster than strftime(). It's also faster in Python 2, about 2-3 times as fast.

    Faster again in Python 3 is the "old" style string interpolation:

    '%02d/%02d/%d' % (now.month, now.day, now.year)
    

    about 5 times faster, but I've found this one to be slower for Python 2.

    Another option, but only 1.5 times faster, is to use time.strftime() instead of datetime.strftime():

    time.strftime('%m/%d/%Y', now.timetuple())
    

    Finally, how are you constructing the datetime object to begin with? If you are converting strings to datetime (with strptime() for example), it might be faster to convert the incoming string version to the outgoing one using string slicing.