Time formatting and date suffixes

John Machin sjmachin at lexicon.net
Mon Jul 25 20:44:56 EDT 2005


Jeffrey E. Forcier wrote:
> This seems like a dead simple question, as it's so rudimentary I  can't 
> believe it hasn't been addressed before. I'm using the  time.strftime() 
> function (actually the mxDateTime implementation, but  they're 
> compatible so it shouldn't matter) to spit out fairly basic  date 
> formats, to wit:
> 
> January 25th, 2005
> 
> The various and sundry date objects in both mxDateTime and Python  
> proper's time/datetime don't seem to have anything anywhere dealing  
> with the 'th' suffix on the date. So in other words, I can use  
> strftime() to get 'January 25, 2005' but don't see anything dealing  
> with outputting the suffixes like 'th', 'nd' and the like. Googling  
> around and searching this list's archives aren't turning anything up,  
> either.
> 
> Am I missing something obvious, or is it just really, really frowned  
> upon to use such a locale-specific function as English date suffixes?
> 

I think the lack of facility is probably due to there being not much 
call for that sort of thing -- people doesn't usually go for the "third 
day after Michaelmas in the year of our Lord two thousand and five, at 
ten o'clock in the forenoon" style these days. If you don't use text, 
but stick with the recognisable unambiguous ISO standard format 
(2005-01-25), you don't have to worry about locales. However I guess you 
have to keep the PHB happy; you can write your own routine in a few lines.

Hint:

if 4 <= day <= 20 or 24 <= day <= 30:
     suffix = "th"
else:
     suffix = ["st", "nd", "rd"][day % 10 - 1]

HTH,
John





More information about the Python-list mailing list