Date formatting in Python

Table of Contents

date object methods

today(): Returns the current date.

replace(year, month, day): Returns a new date object with the specified year, month, and day.

strftime(format): Formats the date as a string using the specified format string. For example, date.strftime("%Y-%m-%d") would return a string in the format "YYYY-MM-DD".

weekday(): Returns the day of the week as an integer, where Monday is 0 and Sunday is 6.

isoweekday(): Returns the ISO day of the week as an integer, where Monday is 1 and Sunday is 7.

year: Returns the year as an integer.

month: Returns the month as an integer.

day: Returns the day of the month as an integer.

ctime(): Returns a string representing the date and time in a human-readable format, such as "Tue Feb 15 00:00:00 2023".

toordinal(): Returns the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1.

fromisoformat(date_string): Returns a date object from a string in ISO format, such as "2023-02-15".

Suffix

def suffix(day): # day == datetime object
    if 11 <= day.day <= 13:
        return 'th'
    else:
        return {1: 'st', 2: 'nd', 3: 'rd'}.get(day.day % 10, 'th')

use as:

day_name = day.strftime("%a %d" + suffix_str + " %b")

⬇︎

'Wed 22nd Feb 08:00'

links

social