Alexander Bird Alexander Bird - 1 year ago 76
Python Question

python format datetime with "st", "nd", "rd", "th" (english ordinal suffix) like PHP's "S"

I would like a python datetime object to output (and use the result in django) like this:

Thu the 2nd at 4:30

But I find no way in python to output
, or
like I can with PHP datetime format with the
string (What they call "English Ordinal Suffix") (

Is there a built-in way to do this in django/python?
isn't good enough (

Django has a filter which does what I want, but I want a function, not a filter, to do what I want. Either a django or python function will be fine.

Answer Source

The django.utils.dateformat has a function format that takes two arguments, the first one being the date (a [[or datetime.datetime]] instance, where datetime is the module in Python's standard library), the second one being the format string, and returns the resulting formatted string. The uppercase-S format item (if part of the format string, of course) is the one that expands to the proper one of 'st', 'nd', 'rd' or 'th', depending on the day-of-month of the date in question.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download