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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 30 other followers

%d bloggers like this: