Python Tutorial Python Advanced Python References Python Libraries

Python - strftime() Method



The strftime method is defined under datetime, date and time classes of datetime module. It is used to format datetime, date or time objects in more readable format.

To work with strftime() method, the datetime module or classes like datetime, date or time from datetime module must be imported in the current script. In the example below, the module is datetime imported. See the example below for syntax.

import datetime as dt
x = dt.datetime(2019, 10, 5, 10, 15, 20)
print("Formatting a datetime object:")
print(x.strftime("%d/%m/%Y"))
print(x.strftime("%d %B,%Y"))
print(x.strftime("%d %B,%Y  %H:%M:%S"))

y = dt.date(2019, 10, 5)
print("\nFormatting a date object:")
print(y.strftime("%d/%m/%Y"))
print(y.strftime("%d %B,%Y"))

z = dt.time(10, 15, 20)
print("\nFormatting a time object:")
print(z.strftime("%H:%M:%S"))
print(z.strftime("%H hours %M minutes %S seconds"))

The output of the above code will be:

Formatting a datetime object:
05/10/2019
05 October,2019
05 October,2019  10:15:20

Formatting a date object:
05/10/2019
05 October,2019

Formatting a time object:
10:15:20
10 hours 15 minutes 20 seconds

The format code list

The table below shows all the format codes which can be used with strftime() method.

DirectiveDescriptionExample
%yYear as a zero-padded decimal number, short version(without century)01, 02, …, 19, …,99
%-yYear as decimal number, short version(without century)1, 2, …, 19, …,99
%YYear, full version2018
%bMonth name, short versionDec
%BMonth name, full versionDecember
%mMonth in a number as a zero-padded decimal number01, 09, 11, 12
%-mMonth in a number as decimal number1, 9, 11, 12
%dDay of month as a zero-padded decimal number01, 02, ….,31
%-dDay of month as decimal number1, 2, ….,31
%HHour in 24 hr format as a zero-padded decimal number01, 09, 17, 23
%-HHour in 24 hr format as decimal number1, 9, 17, 23
%IHour in 12 hr format as a zero-padded decimal number01, 09, 11, 12
%-IHour in 12 hr format as decimal number1, 9, 11, 12
%MMinute as a zero-padded decimal number01, 02, …,59
%-MMinute as decimal number1, 2, …,59
%SSecond as a zero-padded decimal number01, 02, …,59
%SSecond as decimal number1, 2, …,59
%fMicrosecond123456 (000000-999999)
%pAM/PMPM
%jDay of the year as a zero-padded decimal number001, 002, ..., 366
%-jDay of the year as a decimal number001, 002, ..., 366
%aWeekday, short versionMon
%AWeekday, full versionMonday
%wWeekday in a number2 (0-6 for Sun-Sat)
%zUTC offset in +HHMM or -HHMM format+0530
%ZTime zone nameCST
%UWeek number of the year, Sunday as the first day of the week00, 01, ..., 53
%WWeek number of the year, Monday as the first day of the week00, 01, ..., 53
%cLocal version of date and timeSun Feb 10 08:30:45 2019
%xLocal version of date05/15/18
%XLocal version of time0.3546875
%%A % character%

❮ Python - Dates