Frequently used character code in DateTime
- %a: Displays three characters of the weekday, e.g. Wed.
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("%a"))
Output
Sat
- %A: Displays name of the weekday, e.g. Wednesday.
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("%A"))
Output
Saturday
- %B: Displays the month, e.g. May.
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("%B"))
Output
May
- %w: Displays the weekday as a number, from 0 to 6, with Sunday being 0.
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("%w"))
Output
6
- %m: Displays month as a number, from 01 to 12.
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("%m"))
Output
5
- %p: Define AM/PM for time.
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("%p"))
Output
PM
- %y: Displays year in two-digit format, i.e “20” in place of “2020”.
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("% y"))
Output
18
- %f: Displays microsecond from 000000 to 999999.
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("% f"))
Output
000013
- %j: Displays number of the day in the year, from 001 to 366.
import datetime
x = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)
print(x.strftime("%j"))
Output
132
Formatting Dates in Python
In different regions of the world, different types of date formats are used and for that reason usually, programming languages provide a number of date formats for the developed to deal with. In Python, it is dealt with by using a liberty called DateTime. It consists of classes and methods that can be used to work with data and time values.
Required library
import datetime
Contact Us