Python time strptime() function
The strptime() function in Python is used to format and return a string representation of date and time. It takes in the date, time, or both as an input, and parses it according to the directives given to it. It raises ValueError if the string cannot be formatted according to the provided directives.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
- date_time_string: It is a necessary string parameter where the date to be formatted is provided.
- directive: This parameter represents the condition for parsing the given string. It is also a necessary parameter.
The following tables list the supported directives in python.
format code meaning example %a Abbreviated weekday name Sun, Mon %A Full weekday name Sunday, Monday %w Weekday as decimal number 0…6 %d Day of the month as a zero-padded decimal 01, 02 %b Abbreviated month name Jan, Feb %m month as a zero padded decimal number 01, 02 %B Full month name January, February %y year without century as a zero padded decimal number 99, 00 %Y year with century as a decimal number 2000, 1999 %H hour(24 hour clock) as a zero padded decimal number 01, 23 %I hour(12 hour clock) as a zero padded decimal number 01, 12 %p locale’s AM or PM AM, PM %M Minute as a zero padded decimal number 01, 59 %S Second as a zero padded decimal number 01, 59 %f microsecond as a decimal number, zero padded on the left side 000000, 999999 %z UTC offset in the form +HHMM or -HHMM %Z Time zone name %j day of the year as a zero padded decimal number 001, 365 %U Week number of the year (Sunday being the first) 0, 6 %W Week number of the year 00, 53 %c locale’s appropriate date and time representation Mon Sep 30 07:06:05 2013 %x locale’s appropriate date representation 11/30/98 %X locale’s appropriate time representation 10:03:43 %% A literal ‘%’ character %
Examples 1: Python string to date
time.struct_time(tm_year=1996, tm_mon=12, tm_mday=2, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=337, tm_isdst=-1)
Example 2: Python string to date and time
time.struct_time(tm_year=1996, tm_mon=2, tm_mday=12, tm_hour=5, tm_min=53, tm_sec=0, tm_wday=0, tm_yday=43, tm_isdst=-1)
Example 3: Value error
In this example, if time directives will not match then occurred error.
ValueError Raised: unconverted data remains: 3:55:6 ValueError: time data '25::55::26' does not match format '%H::%M::%S'