Python时间 strptime()函数
Python的 strptime()函数用于格式化和返回日期和时间的字符串表示形式。它接受日期、时间或两者作为输入,并根据给它的指令解析它。如果无法根据提供的指令格式化字符串,则会引发 ValueError。
句法:
time.strptime(date_time_srting,directive)
这里,
- date_time_string:它是一个必要的字符串参数,用于提供要格式化的日期。
- 指令:该参数表示解析给定字符串的条件。它也是一个必要的参数。
指令表:
下表列出了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 %
示例 1:迄今为止的Python字符串
Python3
import time
formatted_date = time.strptime(" 02 Dec 1996",
" %d %b %Y")
print(formatted_date)
Python3
import time
print(time.strptime("02/12/1996 5:53","%m/%d/%Y %H:%M"))
Python3
import time as datetime
datetime_str = '08/1/18 3:55:6'
try:
datetime_object = datetime.strptime(datetime_str, '%m/%d/%y')
except ValueError as e:
print('ValueError Raised:', e)
time_str = '25::55::26'
try:
time_object = time.strptime(time_str, '%H::%M::%S')
except ValueError as e:
print('ValueError:', e)
输出:
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)
示例 2:将Python字符串为日期和时间
蟒蛇3
import time
print(time.strptime("02/12/1996 5:53","%m/%d/%Y %H:%M"))
输出:
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)
示例 3:值错误
在此示例中,如果时间指令不匹配,则发生错误。
蟒蛇3
import time as datetime
datetime_str = '08/1/18 3:55:6'
try:
datetime_object = datetime.strptime(datetime_str, '%m/%d/%y')
except ValueError as e:
print('ValueError Raised:', e)
time_str = '25::55::26'
try:
time_object = time.strptime(time_str, '%H::%M::%S')
except ValueError as e:
print('ValueError:', e)
输出:
ValueError Raised: unconverted data remains: 3:55:6
ValueError: time data '25::55::26' does not match format '%H::%M::%S'