Python time strptime() method
Python Time strptime() Method
Description
The strptime() method parses a string representing a time according to the given format. The return value is a struct_time structure returned by gmtime() or localtime().
The format parameter uses the same instructions as strftime(); the default is “%a %b %d %H:%M:%S %Y”, which matches the format returned by ctime().
If the string cannot be parsed according to the given format, or if there is excess data after parsing, a ValueError exception will be raised.
Syntax
The strptime() method has the following syntax:
time.strptime(string[, format])
Parameters
- string − This is a string representation of a time, parsed according to the given format.
-
format − This is a directive for parsing the given string.
Directives
The following directives can be embedded in the format string:
- %a − Abbreviated day of the week
-
%A − Full day of the week
-
%b − Abbreviated month of the month
-
%B − Full month of the month
-
%c − Recommended date and time format
-
%C − Century (year divided by 100, range 00 to 99)
-
%d − Day of the month (01 to 31)
-
%D − Same as %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 – Same as %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 – AM or PM depending on the given time value
-
%r – AM or PM time
-
%R – 24-hour time
-
%S – Seconds
-
%t – Tab character
-
%T – Current time, equivalent to %H:%M:%S
-
%u – 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 is the first week in the current year with at least 4 days and Monday as the first day of the week
- %W – Week number of the year, starting with the first Monday of the week
-
%w – Day of the week, expressed as a decimal number, with Sunday as 0
-
%x – Preferred date representation without time
-
%X – Preferred time representation without date
-
%y – Year without century (range 00 to 99)
-
%Y – Year including century
-
%Z or %z – Time zone name or abbreviation
-
%% – Literal % character
Return Value
The return value is the struct_time returned by gmtime() or localtime().
Example
The following example demonstrates the use of the strptime() method.
import time
struct_time = time.strptime("20 04 2023", "%d %m %Y")
print ("tuple : ", struct_time)
When we run the above program, it will produce the following output
tuple : time.struct_time(tm_year=2023, tm_mon=4, tm_mday=20, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=110, tm_isdst=-1)