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 | 一年中的第几天 |
%p | am、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'