Python time strftime() method
Python Time strftime() Method
Description
The strftime() method converts a time represented by a tuple or struct_time returned by gmtime() or localtime() to a string specified by the format argument.
If “t” is not provided, the current time as returned by localtime() is used. format must be a string. If any field in “t” is out of the allowed range, a ValueError exception is raised.
Syntax
The syntax of the strftime() method is as follows –
time.strftime(format[, t])
Parameters
- t – This is the time in seconds to be formatted.
-
format – This directive is used to format a given time.
Directives
The following directives can be embedded in the format string –
- %a – Abbreviated weekday name
-
%A – Full weekday name
-
%b – Abbreviated month name
-
%B – Full month name
-
%c – Preferred date and time representation
-
%C – Century (year divided by 100, range 00 to 99)
-
%d – Day of the month (01 to 31)
-
%D – Equivalent to %m/%d/%y
-
%e – Day of the month (1 to 31)
-
%g – Like %G, but without the century
-
%G – Four-digit year corresponding to the ISO week number (see %V)
-
%h – Equivalent to %b
-
%H – Hour using a 24-hour clock (00 to 23)
-
%I – Hour using a 12-hour clock (01 to 12)
-
%j – Day of the year (001 to 366)
-
%m – Month (01 to 12)
-
%M – Minutes
-
%n – Newline character
-
%p – Displays AM or PM based on the given time value
-
%r – AM and PM time representations
-
%R – 24-hour time
-
%S – Seconds
-
%t – Tab character
-
%T – Current time, equivalent to %H:%M:%S
-
%u – Numeric representation of the day of the week (1 to 7), with Monday as 1. Note: On Sun Solaris, Sunday is 1.
-
%U – Week number of the current year, starting with the first Sunday as the first day of week 1.
-
%V – ISO 8601 week number of the current year (01 to 53), where week 1 has at least 4 days and starts with Monday as the first day of the week.
-
%W – Week number of the current year, starting with the first Monday as the first day of week 1.
-
%w – Day of the week as a decimal, with Sunday as 0.
-
%x – Preferred date representation without time.
-
%X – Preferred time representation without date.
-
%y – Year (range 00 to 99)
-
%Y – Year including century
-
%Z or %z – Time zone, name, or abbreviation
-
%% – Use the percent sign directly
Return Value
This method does not return any value.
Example
The following example shows the use of the strftime() method.
import time
t = (2023, 4, 20, 10, 39, 45, 1, 48, 0)
t = time.mktime(t)
print (time.strftime("%b %d %Y %H:%M:%S", time.localtime(t)))
When we run the above program, it produces the following output –
Apr 20 2023 10:39:45