Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 340
skittles789 Avatar asked Apr 19 '17 11:04

skittles789


People also ask

What is the difference between Strptime and Strftime?

strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.

What is now Strftime?

The strftime() function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation. Syntax : strftime(format) Returns : It returns the string representation of the date or time object.

Why do we use Strftime?

The strftime converts date object to a string date. Where format is the desired format of date string that user wants. Format is built using codes shown in the table below...

Does Python have a time type?

In Python, date and time are not a data type of their own, but a module named datetime can be imported to work with the date as well as time. Python Datetime module comes built into Python, so there is no need to install it externally. Python Datetime module supplies classes to work with date and time.


1 Answers

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.

like image 89
mhawke Avatar answered Nov 24 '22 03:11

mhawke