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.
strptime
, the string-to-timestamp function. This question is aboutstrftime
, the timestamp-to-string function. – Cockrell