silijon silijon - 2 months ago 8
Python Question

Python time formatting different in Windows

I'm probably missing an obvious platform difference that I should be accommodating but I'm getting this when trying to do a time format (Python2.7)...

in Linux env:

>>> import time
>>> time.strftime("%a, %d-%b-%Y %T GMT", time.gmtime())
'Tue, 29-May-2012 21:42:04 GMT'


in Windows:

>>> import time
>>> time.strftime("%a, %d-%b-%Y %T GMT", time.gmtime())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Invalid format string


The tuples returned from time.gmtime() appear to be the same, so I'm not completely sure what I need to change.

Answer

In general, you'll find that python time.strftime() supports the same set of format specifiers as the platform (or that platform's libc to be more specific) it runs on. However, only a subset of these is portable. See http://docs.python.org/library/time.html for a list. To quote the docs:

Additional directives may be supported on certain platforms, but only the ones listed here have a meaning standardized by ANSI C.

In this case, %T can be replaced by %H:%M:%S.