Use the strptime () method for time operations in Python, pythonstrptime
The strptime () method indicates the time string according to the format. The returned value is gmtime () or localtime () returned by struct_time ().
The format parameter uses the same command to use strftime (); It defaults to "% a % B % d % H: % M: % S % Y" matched ctime () format returned.
ValueError is suspended if the string cannot be parsed by format, or if it has excess data after parsing.
Syntax
The syntax of the strptime () method is as follows:
time.strptime(string[, format])
Parameters
- String -- this is the time when the string format will be parsed Based on the given format.
- Format -- this is the instruction that will be used to parse the given string.
The following command can embed a format string:
Command
- % A-abbreviated day of the week
- % A-complete day of the week
- % B-abbreviated month name
- % B-complete month name
- % C-expression of the preferred date and time
- % C-century value (year divided by 100, range: 00 to 99)
- % D-the day of the month (01? 31)
- % D-similar to % m/% d/% y
- % E-the day of the month (1? 31)
- % G-similar to % G, but not Century
- % G-year corresponding to the four-digit ISO week (see % V)
- % H-similar to % B
- % H-hour, in 24-hour format (00? 23)
- % I-hour, in 12-hour format (01? 12)
- % J-which day of the year (001? 366)
- % M-month (01? 12)
- % M-min
- % N-linefeed
- % P-according to the given time value am or pm
- % R-symbol of the time in the morning and afternoon: am/pm
- % R-time in 24-hour format
- % S-second
- % T-Tab
- % T-current time, equal to % H: % M: % S
- % U-workday is a number (1 to 7), Monday = 1. Warning Sunday = 1 on Sun Solaris
- % U-the number of weeks in the current year. The first Sunday is the first day of the first week.
- % V-the number of weeks of ISO 8601 of the current year (01 to 53), of which week 1st is the first week of at least four days of the current year, and Monday is the first day of the week.
- % W-the week number of the current year, and the first Monday as the first day of the first week
- % W-week is a decimal number, Sunday = 0
- % X-date representation without time
- % X-time representation with no date preference
- % Y-century-free year (range: 00 to 99)
- % Y-this year, including Century
- % Z or % z-time zone or name or abbreviation
- %-Text % characters
Return Value
Returns the value of gmtime () or localtime () returned by struct_time.
Example
The following example shows how to use the strptime () method.
#!/usr/bin/pythonimport timestruct_time = time.strptime("30 Nov 00", "%d %b %y")print "returned tuple: %s " % struct_timeWhen we run above program, it produces following result:returned tuple: (2000, 11, 30, 0, 0, 0, 3, 335, -1)