
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How do I display the date, like "Aug 5th", using Python's strftime?
It is not possible to get a suffix like st, nd, rd and th using the strftime function. The strftime function doesn't have a directive that supports this formatting. You can create your own function to figure out the suffix and add it to the formatting string you provide.
Example
from datetime import datetime now = datetime.now() def suffix(day): suffix = "" if 4 <= day <= 20 or 24 <= day <= 30: suffix = "th" else: suffix = ["st", "nd", "rd"][day % 10 - 1] return suffix my_date = now.strftime("%b %d" + suffix(now.day)) print(my_date)
Output
This will give the output −
Jan 15th
- Related Articles
- How do I display the current date and time in an Android application?
- How do I display the current date and time in an iOS application?
- How do I calculate the date six months from the current date using the datetime Python module?
- How do I customize the display of edge labels using networkx in Matplotlib?
- How do I get the current date in JavaScript?
- How do I display tooltips in Tkinter?
- How do I display only the visible text with jQuery?
- Display different variables in MySQL using LIKE?
- How can I display Java date as '12/04/2019'
- How do I get the current date and time in JavaScript?
- How do I get the creation date of a MySQL table?
- How do I create a date picker in tkinter?
- How do I specify an arrow-like linestyle in Matplotlib?
- How do I display the indexes of a collection in MongoDB?
- How do I display an alert dialog on Android?

Advertisements