Python Format Datetime with "St", "Nd", "Rd", "Th" (English Ordinal Suffix) Like PHP's "S"

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

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.

How to change datetime.date to st,nd,rd,th when changing to string using strftime

you're looking for the ordinal numeral. borrowing from Ordinal numbers replacement, you can use

import datetime

def ordinal(n: int) -> str:
"""
derive the ordinal numeral for a given number n
"""
return f"{n:d}{'tsnrhtdd'[(n//10%10!=1)*(n%10<4)*n%10::4]}"

date1 = datetime.date(2021, 1, 26)

dayOrdinal = ordinal(date1.day)

date1_string = date1.strftime(f'%A, %B {dayOrdinal}, %Y')
# 'Tuesday, January 26th, 2021'

How to parse date days that contain st, nd, rd, or th?

You can use regex to replace st, nd, rd, th with an empty string:

import re
def solve(s):
return re.sub(r'(\d)(st|nd|rd|th)', r'\1', s)

Demo:

>>> datetime.strptime(solve('1st January 2014'), "%d %B %Y")
datetime.datetime(2014, 1, 1, 0, 0)
>>> datetime.strptime(solve('3rd March 2014'), "%d %B %Y")
datetime.datetime(2014, 3, 3, 0, 0)
>>> datetime.strptime(solve('2nd June 2014'), "%d %B %Y")
datetime.datetime(2014, 6, 2, 0, 0)
>>> datetime.strptime(solve('1st August 2014'), "%d %B %Y")
datetime.datetime(2014, 8, 1, 0, 0)

Python how to return date as words?

You can use the following format for strftime:

In [1]: from datetime import date

In [2]: date(day=30, month=11, year=2014).strftime('%A %d %B %Y')
Out[2]: 'Sunday 30 November 2014'

Adding the proper suffix to the day number is more complicated:

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

Input format to convert with datetime.strptime

You have a colon (:) instead of a decimal (.) before the %f in your format string.

Change

datetime.strptime("2019-01-06T01:00:24.908821", "%Y-%m-%dT%H:%M:%S:%f")

To

datetime.strptime("2019-01-06T01:00:24.908821", "%Y-%m-%dT%H:%M:%S.%f")

Date Ordinal Output?

Or shorten David's answer with:

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

giving numbers ordinal suffixes in python

You can utilize the natural package to do this (and more).

pip install natural

Then using this code, you can print out ordinals:

>>> from natural import number
>>> number.ordinal(3)
u'3rd'
>>> number.ordinal(1234567)
u'1234567th'

Convert a Particular Dataframe Column Into Customized Date Or Time

Try creating a temporary column:

result['Full_date']=pd.to_datetime(result['Date']+' '+result['Time'])

Then format 'Date' and 'Time'

result['Date']=result['Full_date'].dt.strftime('%b %d, %Y')
result['Time']=result['Full_date'].dt.strftime('%R' '%p')

Ordinal numbers replacement

The package number-parser can parse ordinal words ("first", "second", etc) to integers.

from number_parser import parse_ordinal
n = parse_ordinal("first")

To convert an integer to "1st", "2nd", etc, you can use the following (taken from Gareth on codegolf):

ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n//10%10!=1)*(n%10<4)*n%10::4])

This works on any number:

print([ordinal(n) for n in range(1,32)])

['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th',
'11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th',
'20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th',
'29th', '30th', '31st']


Related Topics



Leave a reply



Submit