Home > python > produce the output of Unix’s date command

produce the output of Unix’s date command

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
About these ads
Categories: python Tags: ,
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.
Follow

Get every new post delivered to your Inbox.

Join 63 other followers

%d bloggers like this: