22 June 2007

strftime helper

I can never remember the syntax for strftime -- so I wrote a little helper for it: strftime_helper.py, which uses pii.py (see previous post, Extending Python's Interactive Interpreter). Here is an interactive session with it:

>>> pd
= pd help =

localet, localed, localedt  - Locale Time, Locale Date, Locale Date & Time
hh24, hh, mm, ss, am, pm    - 24-Hour, Hour, Minute, Second, Am, Pm
dow, dom, doy               - Day Of {Week, Month, & Year} respectively
swoy, mwoy                  - Week Of Year considering either Sunday or Monday
                                as first day of week
yy, yyyy                    - Year without century & Year with century
tz                          - Timezone
mon..sun, monday..sunday    - Weekday in Abbrev or Long form
jan..dec, january..december - Month in Abbrev or Long form

? localet hh24:mm:ss, pm
2007-06-22 19:36:53 formats to
19:36:53 19:36:53, PM
'%X %H:%M:%S, %p'
? jun dom, yyyy (it's a sunday)
2007-06-22 19:38:51 formats to
Jun 22, 2007 (it's a Friday)
"%b %d, %Y (it's a %A)"
? [ENTER] or Control-D
>>> _
"%b %d, %Y (it's a %A)"

Things to note:

  • although the new format directives are easier to remember (dom of day of the month, any of mon, tue, wed, ..., sun for a short weekday name, any of january, feburary, ..., december for a long month name, tz for timezone), a help screen is printed out each time you type pd
  • you end the interactive session with pd by hitting Ctrl-D or by passing it a empty line. The _ variable will be set to the result of pd: the actual format control that strftime interprets

Given Python's friendliness to newbies, there should be a newbie.py supplied with the standard distribution that "simplifies" many such tasks for newbies...