Format Current Date in month in Format [Month Day Suffix, Year] February 12th,2020


Format Current Date in the month 

in Format 

[Month Day Suffix, Year] February 12th,2020


Description:

        Many times we need to handle date in python as per requirements.
There are predefined python's string format directives. They are as follows:


Code Meaning Example
%a Weekday as locale’s abbreviated name. Mon
%A Weekday as locale’s full name. Monday
%w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. 1
%d Day of the month as a zero-padded decimal number. 30
%-d Day of the month as a decimal number. (Platform specific) 30
%b Month as locale’s abbreviated name. Sep
%B Month as locale’s full name. September
%m Month as a zero-padded decimal number. 09
%-m Month as a decimal number. (Platform specific) 9
%y The year without century as a zero-padded decimal number. 13
%Y Year with century as a decimal number. 2013
%H Hour (24-hour clock) as a zero-padded decimal number. 07
%-H Hour (24-hour clock) as a decimal number. (Platform specific) 7
%I Hour (12-hour clock) as a zero-padded decimal number. 07
%-I Hour (12-hour clock) as a decimal number. (Platform specific) 7
%p Locale’s equivalent of either AM or PM. AM
%M Minute as a zero-padded decimal number. 06
%-M Minute as a decimal number. (Platform specific) 6
%S Second as a zero-padded decimal number. 05
%-S Second as a decimal number. (Platform specific) 5
%f Microsecond as a decimal number, zero-padded on the left. 000000
%z UTC offset in the form +HHMM or -HHMM (empty string if the object is naive).
%Z Time zone name (empty string if the object is naive).
%j Day of the year as a zero-padded decimal number. 273
%-j Day of the year as a decimal number. (Platform specific) 273
%U Week number of the year (Sunday as the first day of the week) as a zero-padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. 39
%W Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. 39
%c Locale’s appropriate date and time representation. Mon Sep 30 07:06:05 2013
%x Locale’s appropriate date representation. 09/30/13
%X Locale’s appropriate time representation. 07:06:05
%% A literal '%' character. %



We use the above directives to format out date in the required format.

Example as follows : 



# -*- coding: utf-8 -*-
"""
Created on Tue Feb 17 17:07:31 2020
@author: Sameer Narkhede """
from datetime import datetime as dt

from datetime import date

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

def custom_strftime(format, t):
     return t.strftime(format).replace('{S}', str(t.day) + suffix(t.day))

#Your Code Here
print(custom_strftime('%B {S}, %Y', dt.now()))


    In this example, we used datetime to handle dates in python. Firstly I've imported the required package. Then created a function to get the suffix for the day named as a suffix with one parameter d.
      here, I added

 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th')

to get  suffix for the day. {1:'st',2:'nd',3:'rd'} is type of dictionary which stoted the 'st','nd','rd' . and get is the dictionary function to get element from dictionary.

Syntax : dictionary.get(key, value)

here,

*key(Required.):
     The key of the item you want to return the value from

*value(Optional.)
     Value to return if the specified key does not exist.
Default value None

Example with suffix function :



1)suffix(1)
Output: 'st'

2)suffix(2)
Output: 'nd'

3)suffix(3)
Output: 'rd'

4)suffix(4)
Output: 'th'


      custom_strftime(format, t) is another function to format the date .we pass date with parameter t. and format is the string format to format the date given by param t.
       Here,
             '{s}' is the dummy char sequence which we replace with day and suffix
      as '{s}' =>> 1st



      The format for formatting date is '%B {S}, %Y' Where %B prints Current Month as "February", {S} is the replacement string which is replaced with day with the suffix as 1st and %Y prints the Year of the current date. 

Example:


print(custom_strftime('%B {S}, %Y', dt.now()))

Output as ==>> February 17th, 2020 


If you found any difficulty with this blog you can contact me by using a comment or ping me on my Gmail: narkhedesam@gmail.com


Comments