Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 st, nd, rd, or th like I can with PHP datetime format with the S string (What they call "English Ordinal Suffix") (http://uk.php.net/manual/en/function.date.php).

Is there a built-in way to do this in django/python? strftime isn't good enough (http://docs.python.org/library/datetime.html#strftime-strptime-behavior).

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.

like image 943
Alexander Bird Avatar asked Sep 04 '10 23:09

Alexander Bird


People also ask

How do I format a datetime string in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

How do I change date format from YYYY to MM DD in Python?

yyyy-mm-dd stands for year-month-day . We can convert string format to datetime by using the strptime() function. We will use the '%Y/%m/%d' format to get the string to datetime.

What is the data type of datetime in Python?

A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.


2 Answers

The django.utils.dateformat has a function format that takes two arguments, the first one being the date (a datetime.date [[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.

like image 65
Alex Martelli Avatar answered Oct 22 '22 14:10

Alex Martelli


dont know about built in but I used this...

def ord(n):     return str(n)+("th" if 4<=n%100<=20 else {1:"st",2:"nd",3:"rd"}.get(n%10, "th")) 

and:

def dtStylish(dt,f):     return dt.strftime(f).replace("{th}", ord(dt.day)) 

dtStylish can be called as follows to get Thu the 2nd at 4:30. Use {th} where you want to put the day of the month ("%d" python format code)

dtStylish(datetime(2019, 5, 2, 16, 30), '%a the {th} at %I:%M') 
like image 28
Frosty Snowman Avatar answered Oct 22 '22 12:10

Frosty Snowman