Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display the date, like "May 5th", using pythons strftime? [duplicate]

Possible Duplicate:
Python: Date Ordinal Output?

In Python time.strftime can produce output like "Thursday May 05" easily enough, but I would like to generate a string like "Thursday May 5th" (notice the additional "th" on the date). What is the best way to do this?

like image 454
Buttons840 Avatar asked May 05 '11 01:05

Buttons840


People also ask

How do I display the date in python?

today() method to get the current local date. By the way, date. today() returns a date object, which is assigned to the today variable in the above program. Now, you can use the strftime() method to create a string representing date in different formats.

What is Strftime function in Python?

The strftime() function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation. Returns : It returns the string representation of the date or time object.

What does date () do in Python?

The date class is used to instantiate date objects in Python. When an object of this class is instantiated, it represents a date in the format YYYY-MM-DD. Constructor of this class needs three mandatory arguments year, month and date.


2 Answers

strftime doesn't allow you to format a date with a suffix.

Here's a way to get the correct suffix:

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

found here

Update:

Combining a more compact solution based on Jochen's comment with gsteff's answer:

from datetime import datetime as dt  def suffix(d):     return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th')  def custom_strftime(format, t):     return t.strftime(format).replace('{S}', str(t.day) + suffix(t.day))  print custom_strftime('%B {S}, %Y', dt.now()) 

Gives:

May 5th, 2011

like image 83
Acorn Avatar answered Sep 27 '22 19:09

Acorn


This seems to add the appropriate suffix, and remove the ugly leading zeroes in the day number:

#!/usr/bin/python  import time  day_endings = {     1: 'st',     2: 'nd',     3: 'rd',     21: 'st',     22: 'nd',     23: 'rd',     31: 'st' }  def custom_strftime(format, t):     return time.strftime(format, t).replace('{TH}', str(t[2]) + day_endings.get(t[2], 'th'))  print custom_strftime('%B {TH}, %Y', time.localtime()) 
like image 20
gsteff Avatar answered Sep 27 '22 19:09

gsteff