PHP’s date() function in Python
7th October 2003
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.
More recent articles
- Weeknotes: the Datasette Cloud API, a podcast appearance and more - 1st October 2023
- Things I've learned about building CLI tools in Python - 30th September 2023
- Talking Large Language Models with Rooftop Ruby - 29th September 2023
- Weeknotes: Embeddings, more embeddings and Datasette Cloud - 17th September 2023
- Build an image search engine with llm-clip, chat with models with llm chat - 12th September 2023
- LLM now provides tools for working with embeddings - 4th September 2023
- Datasette 1.0a4 and 1.0a5, plus weeknotes - 30th August 2023
- Making Large Language Models work for you - 27th August 2023
- Datasette Cloud, Datasette 1.0a3, llm-mlc and more - 16th August 2023
- How I make annotated presentations - 6th August 2023