DateFormat with Python

My early background in programming is in ColdFusion. Since I found python I do not really use ColdFusion for much any more but it is still one of my favorite languages. One of the features I missed most about ColdFusion is the DateFormat() built-in function. Python's default date formatting syntax is arcane in my opinion and very difficult to remember at best. I always find myself going back to the documentation to figure it out. Worry no more. Introducing ... DateFormat() for python based on the ColdFusion DateFormat() function. It is not a terribly unique name by any means but it takes all the guess work out of remembering how to format a date by using a string mask to show how you want the date to appear. The following values can be used in the mask:

  • d: Day of the month as digits; no leading zero for single-digit days.
  • dd: Day of the month as digits; leading zero for single-digit days.
  • ddd: Day of the week as a three-letter abbreviation.
  • dddd: Day of the week as its full name.
  • m: Month as digits; no leading zero for single-digit months.
  • mm: Month as digits; leading zero for single-digit months.
  • mmm: Month as a three-letter abbreviation.
  • mmmm: Month as its full name.
  • yy: Year as last two digits; leading zero for years less than 10.
  • yyyy: Year represented by four digits.

The following masks tell how to format the full date and cannot be combined with other masks:

  • short: equivalent to m/d/yy.
  • medium: equivalent to mmm d, yyyy.
  • long: equivalent to mmmm d, yyyy.
  • full: equivalent to dddd, mmmm d, yyyy.

Example usage is:

>>>import datetime
>>>today = datetime.datetime.today()
>>> DateFormat(today, 'mm-dd-yyyy')
'09-20-2007'
>>>DateFormat(today, 'ddd, mmm d, yyyy')
'Thu, Sep 20, 2007'
>>>DateFormat(today, 'm/d/yy')
'9/20/07'
>>>DateFormat(today, 'full')
'Thursday, September 20, 2007'

Download it here

Comments