• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

如何学习Python time模块

python 搞代码 4年前 (2022-01-09) 30次浏览 已收录 0个评论

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 类中各属性的含义

来1源gaodai#ma#com搞*代#码1网

表 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 点整到现在过了多少秒。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:如何学习Python time模块

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址