Posts Tagged ‘unix date’

produce the output of Unix’s date command

April 6, 2012 Leave a comment

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?

I posed this question today on the python-list and I got the following answer from Chris R.:

From POSIX (

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"

   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
Categories: python Tags: ,