Posts Tagged ‘unix date’
produce the output of Unix’s date command
April 6, 2012
Leave a comment
Problem
You want to get the same output as Unix’s date command but you don’t want to make an external call. How to produce this output in pure Python?
Solution
I posed this question today on the python-list and I got the following answer from Chris R.:
From POSIX (http://pubs.opengroup.org/onlinepubs/009695399/utilities/date.html): When no formatting operand is specified, the output in the POSIX locale shall be equivalent to specifying: date "+%a %b %e %H:%M:%S %Z %Y" Therefore: from time import strftime print strftime("%a %b %e %H:%M:%S %Z %Y") But note that `date` is locale-sensitive; imitating that would be a bit more complicated.
Thus, the code snippet:
from time import strftime print strftime("%a %b %e %H:%M:%S %Z %Y") # sample output: # Thu Apr 5 23:55:56 CEST 2012