python time.strftime()方法,格式化输出时间

time.strftime()方法

python time模块中的strftime()可以将一个结构化的时间格式化为参数指定格式的时间字符串,比如%Y-%m-%d %H:%M:%S。strftime()可以分三个部分来理解记忆,分别是str相对于str()函数,即转化为字符串,f则是format()格式化的意思,然后便是time部分了。


语法

strftime(format[, tuple]) -> string

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

    Convert a time tuple to a string according to a format specification.
    See the library reference manual for formatting codes. When the time tuple
    is not present, current time as returned by localtime() is used.
    
    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.

参数

参数描述
format必须参数,指定格式化方式,比如%Y-%m-%d %H:%M:%S
tuple可选参数,指定需要被格式化的时间(结构化的时间),比如time.struct_time的数据结构

format格式化方法的各个运算符

运算符描述
%Y输出完整年份
%m月份01至12
%d当月的第几天,介于01至31之间
%H小时数,介于00至23之间
%M分钟数,介于00至59之间
%S秒数,介于00至59之间
%a本地星期名称简写
%A本地星期全称
%b本地月份简写
%B本地月份全称
%c本地日期和时间的字符串,比如23/03/06 13:59:00
%f微秒
%I第几个小时,12小时制,介于0至11之间
%j一年中的第几天
%pam、pm标识符
%U一年中的星期数,00至53之间,以星期天为一周的开始
%w一个星期中的第几天
%W一年中的星期数,以星期一为一周的开始
%x本地日期字符串,如23/03/06
%X本地时间字符串,如13:59:00
%y年份,两位数,介于00至99之间
%z相对于UTC时区的偏移量
%Z时区名称
%%“%”字符

strftime()实例代码

>>> import time
>>> time.strftime('%Y-%m-%d %H:%M:%S') #format是必须参数,类似print()中格式化输出的用法
'2023-03-06 14:09:28'
>>> time.strftime('%Y-%m-%d', time.localtime()) #time.localtime()方法基于当下时间的结构化时间
'2023-03-06'

全栈后端 / Python库 :









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