Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I display the date, like "Aug 5th", using Python's strftime?
Python's strftime() function doesn't directly support ordinal suffixes like "st", "nd", "rd", and "th". You need to create a custom function to determine the appropriate suffix and combine it with strftime() formatting.
Creating a Suffix Function
First, let's create a helper function that determines the correct ordinal suffix for any day ?
def get_suffix(day):
if 4 <= day <= 20 or 24 <= day <= 30:
return "th"
else:
return ["st", "nd", "rd"][day % 10 - 1]
# Test the function
for day in [1, 2, 3, 11, 21, 22, 23]:
print(f"Day {day}: {day}{get_suffix(day)}")
Day 1: 1st Day 2: 2nd Day 3: 3rd Day 11: 11th Day 21: 21st Day 22: 22nd Day 23: 23rd
Formatting Date with Ordinal Suffix
Now combine the suffix function with strftime() to display formatted dates ?
from datetime import datetime
def get_suffix(day):
if 4 <= day <= 20 or 24 <= day <= 30:
return "th"
else:
return ["st", "nd", "rd"][day % 10 - 1]
now = datetime.now()
formatted_date = now.strftime("%b %d") + get_suffix(now.day)
print(formatted_date)
# Example with specific date
specific_date = datetime(2024, 8, 5)
formatted_specific = specific_date.strftime("%b %d") + get_suffix(specific_date.day)
print(formatted_specific)
Jan 15th Aug 5th
Complete Date Formatting Function
Here's a reusable function that handles the entire formatting process ?
from datetime import datetime
def format_date_with_suffix(date_obj, format_string="%b %d"):
def get_suffix(day):
if 4 <= day <= 20 or 24 <= day <= 30:
return "th"
else:
return ["st", "nd", "rd"][day % 10 - 1]
base_format = date_obj.strftime(format_string)
return base_format + get_suffix(date_obj.day)
# Examples
today = datetime.now()
birthday = datetime(2024, 12, 22)
print(format_date_with_suffix(today))
print(format_date_with_suffix(birthday, "%B %d"))
print(format_date_with_suffix(datetime(2024, 3, 1), "%A, %B %d"))
Jan 15th December 22nd Friday, March 1st
How the Suffix Logic Works
The suffix determination follows English ordinal number rules:
- Days 4-20 and 24-30 use "th"
- Days ending in 1 use "st" (except 11th)
- Days ending in 2 use "nd" (except 12th)
- Days ending in 3 use "rd" (except 13th)
Conclusion
Since strftime() doesn't support ordinal suffixes, create a custom function to determine the suffix and concatenate it with the formatted date. This approach gives you full control over date formatting with proper English ordinals.
