PHP’s date() function in Python
In switching from PHP to Python I’m discovering an increasing number of PHP functions that I’ve learnt to rely on but have no direct equivalent in the Python standard library. Often Python simply provides a different way of approaching the problem, but old habits die hard and I’ve been replicating some of PHP’s functionality in Python for my own personal use.
Python 2.3 introduced the datetime module, which has comprehensive support for performing calculations on dates. Users of earlier Python versions can still benefit from the module thanks to a pure Python implementation available here. datetime objects can be formatted as strings using the strftime method, documented here; PHP offers a similar function. strftime() is a powerful function which takes full account of the current locale when formatting dates. PHP’s date() function ignores the locale but provides a far richer set of formatting options, including my favourite: the ability to display a date with an ordinal, for example “7th October”.
I’ve always preferred date(), so I’ve ported it to to Python. My version supports most of PHP’s date format options, raising a NotImplemented exception for any that are unsupported. Usage looks like this:
>>> import datetime
>>> from DateFormat import DateFormat
>>> d = datetime.datetime.now()
>>> df = DateFormat(d)
>>> print df.format('jS F Y H:i')
The class works using a neat piece of introspection. Each of the available formatting options is implemented as a method of the class which returns that part of the date formatted in the correct way. For example, the ’a’ command (for returning ’am’ or ’pm’ in lower case) looks like this:
def a(self):
'"am" or "pm"'
if self.date.hour > 12:
return 'pm'
else:
return 'am'
The format method simply cycles through the characters in the format string, attempting to call the method of that name each time round using getattr(). If a method doesn’t exist (i.e the character isn’t one of the special formatting commands) a try/except block catches the thrown AttributeError. The whole method looks like this:
def format(self, formatstr):
result = ''
for char in formatstr:
try:
result += str(getattr(self, char)())
except AttributeError:
result += char
return result
I might alter the interface a bit in the future, maybe creating an extended version of the datetime class itself, but for the moment this serves my purposes just fine.
Scott Johnson - 7th October 2003 12:06 - #
One question - What's a 'try/catch blog'? :-)
Danny Shepherd - 7th October 2003 12:47 - #
Cool --
One Pythonic thing that may not make a huge difference when working with short strings like this, but definitely becomes a problem when creating longer strings a piece at a time is that the
+=operation needs to reallocate the entire string everytime to add to the end. Instead use the idiom (apologies if this is obvious, but traffic on comp.lang.python indicates that it's not widely known) of building your string by appending substrings to a list, then returning"".join(listOfSubstrings)to create the final string for output.Much faster.
Bg Porter - 7th October 2003 14:30 - #
John Beimler - 7th October 2003 15:35 - #
ummm .... 12:01 is PM, not AM.
Eric Scheid - 8th October 2003 10:06 - #
Simon Willison - 8th October 2003 14:41 - #
>>> import time >>> from DateFormat import DateFormat >>> d = time.time() >>> df = DateFormat(d) >>> print df.format('jS F Y H:i')Add this code to DateFormat.py:import time class Date: def __init__(self, *arg): self.year = arg[0] self.month = arg[1] self.day = arg[2] self.hour = arg[3] self.minute = arg[4] self.second = arg[5] self.weekday = arg[6] self.julian_day = arg[7] self.dst = arg[8] class DateFormat: """ Takes a time.time() """ weekdays = 'Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split() months = 'January February March April May June July August September October November December'.split() def __init__(self, d): self.date = Date(*time.gmtime(d)) ...dblank - 21st November 2004 04:35 - #
def s(self, s):should be:def s(self):dsblank - 21st November 2004 05:02 - #
kit - 27th September 2005 10:41 - #
kumar - 1st August 2006 10:53 - #