Saturday, January 24, 2015

A small catch in Python documentation (strftime).

Every developer knows datetime.strftime() method, but some don't know that its argument's format is not documented in full in the official documentation.

For example, you won't find any mention of %s directive there which means UNIX epoch time, timestamp. It works (at least with every major version of Python on Linux, FreeBSD, and MacOS), I've tested it a few times myself, it's just not documented.

I recently saw a piece of code where developers, being unaware of such a directive, used custom format string with both datetime.now() and time.time(), a function generator, and on top of it messed with model migrations (it all was about FileField.upload_to if you know what I'm talking about) when they could just use %s.

From other undocumented features you might be interested in these:

%C is a century (%Y//100), could be helpful for complimenting %y or something, I guess.

%u is a weekday number with Monday as 1 and Sunday as 7 (as opposed to %w representing Sunday as 0).

And padding/case modifiers (specifications are for reference only):

%_d (pad with blank),
%-H (no padding),
%0e (pad with zeros),
%^A (uppercase),
%#Z (effectively lowercase for %Z, not useful with anything else).

(Note: They were introduced by GNU extension but work on BSD/MacOS and other modern systems.)

I'm not writing documentation here, but for the sake of completeness, here is the list of all specifications supported by python library on major platforms but not mentioned in Python docs:

%C %D %e %F %G %g %h %k %l %n %R %r %s %T %t %u %V (and modifiers %_* %-* %0* %^* %#* %E* %O*)

Most of them are just shortcuts (like %F, %T, or %D) or simply useless (like %V, %G, %g stuff) but please refer to strftime(3) or standards for explanations.