Python Library Tips: date formatting


Date formatting

In Python you can format date string using following predefined strings ,

%y/%Y –Year %a/A –Week Day %b/B –Month and %d for day

The letter with lowercase (%y/Y%) gives you abbreviated values, say 20 for 2020, Thu for Thursday etc

>>> print( today.strftime("%y %b %a"))
20 Jun Thu
>>> print( today.strftime("%a,%d,%B,%y "))
Thu,18,June,20 

Locale date

Some times your application may be consumed by people for different localities or people from different countries, of course the date and time will be different. Python allows you to format date and time according to locale settings.

>>> print(today.strftime("%c"))
Thu Jun 18 00:00:00 2020
>>> print(today.strftime("%x"))
06/18/20
>>> print(today.strftime("%X"))

Here %c stand for locale’s date and time , %x for locale’s time and %X for locale’s date

You can also use predefined string s for format time . %I/H for 12/24 Hour, %M for Minutes, %S for second and % p for locales’s AM/PM


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.