Python’s date.strftime() slower than str(), split, unpack, and concatenate?

See Python: Tips and Tricks for similar articles.

I was surprised to find that date.strftime() is slower than converting the date to a string, splitting the string into a list, unpacking the list into year, month, and day strings and then concatenating those to format the date:

def date_to_str(date):
    year, month, day = str(date).split("-")
    return f"{month}/{day}/{year}"

Here’s the full test, using the timeit module:

import timeit
import datetime


def date_to_str(date):
    year, month, day = str(date).split("-")
    return f"{month}/{day}/{year}"


today = datetime.date.today()

result_date_to_str = timeit.timeit(
    "date_to_str(today)", number=10000, globals=globals()
)

result_strftime = timeit.timeit(
    'today.strftime("%m/%d/%Y")', number=10000, globals=globals()
)

print("date_to_str:", result_date_to_str)
print("strftime:", result_strftime)

And the results:

date_to_str: 0.011771791
strftime: 0.032107662999999995

The date_to_str() function runs almost 3 times faster than date.strftime().

Strange.

But, of course, we’re talking about nanoseconds.