time 模块主要包含各种提供日期、时间功能的类和函数。该模块既提供了把日期、时间格式化为字符串的功能,也提供了从字符串恢复日期、时间的功能。
在 Python 的交互式解释器中先导入 time 模块,然后输入 [e for e in dir(time) if not e.startswith(‘_’)] 命令,即可看到该模块所包含的全部属性和函数:
>>> [e for e in dir(time) if not e.startswith('_')] ['altzone', 'asctime', 'clock', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'perf_counter', 'process_time', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname']
在 time 模块内提供了一个 time.struct_time 类,该类代表一个时间对象,它主要包含 9 个属性,每个属性的信息如下表所示:
表 1 time.struct_time 类中各属性的含义
字段名 | 字段含义 | 值 |
---|---|---|
tm_year | 年 | 如 2017、2018 等 |
tm_mon | 月 | 如 2、3 等,范围为 1~12 |
tm_mday | 日 | 如 2、3 等,范围为 1~31 |
tm_hour | 时 | 如 2、3 等,范围为 0~23 |
tm_min | 分 | 如 2、3 等,范围为 0~59 |
tm_sec | 秒 | 如 2、3 等,范围为 0~59 |
tm_wday | 周 | 周一为 0,范围为 0~6 |
tm_yday | 一年内第几天 | 如 65,范围 1~366 |
tm_isdst | 夏时令 | 0、1 或 -1 |
比如,Python 可以用 time.struct_time(tm_year=2018, tm_mon=5, tm_mday=2, tm_hour=8, tm_min=0, tm_sec=30, tm_wday=3, tm_yday=1, tm_isdst=0) 很清晰地代表时间。
此外,Python 还可以用一个包含 9 个元素的元组来代表时间,该元组的 9 个元素和 struct_time 对象中 9 个属性的含义是一一对应的。比如程序可以使用(2018, 5, 2, 8, 0, 30, 3, 1, 0)来代表时间。
在日期、时间模块内常用的功能函数如下:
time.asctime([t]):将时间元组或 struct_time 转换为时间字符串。如果不指定参数 t,则默认转换当前时间。
time.ctime([secs]):将以秒数代表的时间转换为时间宇符串。
time.gmtime([secs]):将以秒数代表的时间转换为 struct_time 对象。如果不传入参数,则使用当前时间。
time.localtime([secs]):将以秒数代表的时间转换为代表当前时间的 struct_time 对象。如果不传入参数,则使用当前时间。
time.mktime(t):它是 localtime 的反转函数,用于将 struct_time 对象或元组代表的时间转换为从 1970 年 1 月 1 日 0 点整到现在过了多少秒。
time.perf_counter():返回性能计数器的值。以秒为单位。
time.process_time():返回当前进程使用 CPU 的时间。以秒为单位。
time.sleep(secs):暂停 secs 秒,什么都不干。
time.strftime(format[, t]):将时间元组或 struct_time 对象格式化为指定格式的时间字符串。如果不指定参数 t,则默认转换当前时间。
time.strptime(string[, format]):将字符串格式的时间解析成 struct_time 对象。
time.time():返回从 1970 年 1 月 1 日 0 点整到现在过了多少秒。