python time.strptime()方法,格式化时间转结构化

time.strptime()方法

python time模块的strptime()方法,可以将一个格式化的日期时间,比如%Y-%m-%d %H:%M:%S格式的时间转换为结构化的时间,如time.struct_time结构的时间。


strptime()语法

strptime(string, format) -> struct_time

提示:"->"符号表示指定返回值类型

python源码中对strptime()方法的介绍:

Parse a string to a time tuple according to a format specification.
    See the library reference manual for formatting codes (same as
    strftime()).
    
    Commonly used format codes:
    
    %Y  Year with century as a decimal number.
    %m  Month as a decimal number [01,12].
    %d  Day of the month as a decimal number [01,31].
    %H  Hour (24-hour clock) as a decimal number [00,23].
    %M  Minute as a decimal number [00,59].
    %S  Second as a decimal number [00,61].
    %z  Time zone offset from UTC.
    %a  Locale's abbreviated weekday name.
    %A  Locale's full weekday name.
    %b  Locale's abbreviated month name.
    %B  Locale's full month name.
    %c  Locale's appropriate date and time representation.

参数

参数描述
string必须的参数,格式化的时间字符串,比如"2020-01-01 08:00:30",如果不传递第二个参数,string默认的格式为'%a %b %d %H:%M:%S %Y',即星期简写、月份简写、日、小时、分钟、秒、年份
format可选的参数,指定string参数中的时间格式,而且必须一一对应,使用“-”就必须对应“-”,使用“:”就对应“:”

提示:python日期时间的格式化运算符可参考:strftime()方法中的内容。


返回值

time.struct_time类型的结构化时间。


strptime()实例代码

>>> import time
>>> time.strptime('2020-01-01 08:00:30','%Y-%m-%d %H:%M:%S')
time.struct_time(tm_year=2020, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=0, tm_sec=30, tm_wday=2, tm_yday=1, tm_isdst=-1)
>>> time.strptime('Wed Mar 08 16:23:22 2023') #不传递第二个参数的情况下string的格式
time.struct_time(tm_year=2023, tm_mon=3, tm_mday=8, tm_hour=16, tm_min=23, tm_sec=22, tm_wday=2, tm_yday=67, tm_isdst=-1)

全栈后端 / Python库 :









Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.