(一)Python time strftime() 方法
(1)描述
Python time strftime() 函数用于格式化时间,返回以可读字符串表示的当地时间,格式由参数 format 决定。
(2)语法
strftime()方法语法:
time.strftime(format[, t])
(3)参数
(1)format – 格式字符串。
(2)t – 可选的参数 t 是一个 struct_time 对象。
(4)返回值
返回以可读字符串表示的当地时间。
(5)说明
python中时间日期格式化符号:
%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身
(6)实例
以下实例展示了 strftime() 函数的使用方法:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 通过导入 __future__ 包来兼容 Python3.x print
# 如果使用了 Python3.x 可以删除此行引入
from __future__ import print_function
from datetime import datetime
now = datetime.now() # current date and time
year = now.strftime("%Y") # %Y 四位数的年份表示(000-9999)
print("year:", year)
month = now.strftime("%m") # %m 月份(01-12)
print("month:", month)
day = now.strftime("%d") # %d 月内中的一天(0-31)
print("day:", day)
time = now.strftime("%H:%M:%S")
'''
%H 24小时制小时数(0-23)
%M 分钟数(00=59)
%S 秒(00-59)
'''
print("time:", time)
date_time = now.strftime("%Y-%m-%d, %H:%M:%S")
print("date and time:",date_time)
运行结果如下:
(二)Python time localtime()方法
(1)描述
Python time localtime() 函数类似gmtime(),作用是格式化时间戳为本地的时间。 如果sec参数未输入,则以当前时间为转换标准。
(2)语法
localtime()方法语法:
time.localtime([ sec ])
(3)参数
sec – 转换为time.struct_time类型的对象的秒数。
(4)返回值
该函数没有任何返回值。