time

time是python内置的一个处理时间相关的模块,实际开发过程中会高频使用.

time使用

要使用time模块非常简单,使用import time导入模块即可,后续将介绍一些常用的方法

time方法列表

asctime()

把一个表示时间的元祖转换为字符串,接收一个tuple类型参数,需要9个长度.
前6位位年月日时分秒,第七位表示周几,第8位表示本年内的第多少天.
如果不传入参数,参数默认为localtime()

import time
# 比如 2019-10-21 12:10:12
t = (2018, 8, 21, 12, 10, 12, 2, 0, 0)
print(time.asctime(t))

输出 d Aug 21 12:10:12 2018

localtime()

返回一个当前时间的元祖,可以和asctime()配合使用

import time
print(time.localtime())
print(time.asctime(time.localtime()))

clock()

调用clock()函数时 返回cpu时间或者第一次调用clock()时程序运行时间

import time
print(time.clock())

注意:3.3版本弃用,3.8版本会移除,可以使用下面连个方法来替代

perf_counter()

基准新能测试计时器

import time
print(time.perf_counter(), time.perf_counter_ns())

注:_ns后缀函数表示返回纳秒为单位,后续同

process_time()

统计内核时间与用户cpu时间的总和

import time
print(time.process_time(), time.process_time_ns())

ctime()

返回一个字符串时间 同print(time.asctime(time.localtime()))

import time
print(time.ctime())

gmtime()

返回一个UTC时区的字符串,中国是PRC时区(peoples republic of china,东八区),实际时间为UTC+8

import time
print(time.gmtime())

mktime()

将一个元祖格式转换为时间戳,float类型

import time
print(time.mktime(time.localtime()))

sleep()

线程推迟指定时间后运行,单位为秒

import time
print(time.sleep(5), "程序五秒后执行")

strftime()

使用频率非常高,将时间元祖转换为一个格式化字符串.
没有传入时间元祖,将默认调用time.localtime()

import time
print(time.strftime("%y-%m-%d %I:%M:%S %z"))

常用format格式

  • 年份 %Y 4位 %y 2位表示
  • 月份 %m 1-12
  • 日 %d 1-31
  • 时 %H 24小时制 %I 12小时制的时
  • 分 %M分
  • 秒 %S秒 %s秒.毫秒
  • 时区 %z相对UTC时区的偏移量

time.strptime()

也是一个使用频率非常高的方法,将一个时间字符串转换成元组,格式同上

import time
print(time.strptime("19-08-21 12:03:16","%ys-%m-%d %I:%M:%S"))

输出time.struct_time(tm_year=2019, tm_mon=8, tm_mday=21, tm_hour=0, tm_min=3, tm_sec=16, tm_wday=2, tm_yday=233, tm_isdst=-1)

time()

高频使用函数,返回时间戳,float类型,time_ns()返回int类型

import time
print(time.time(), time.time_ns())
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 开始之前,首先要说明这几点: 1.在Python中,通常有这几种方式来表示时间:1)时间戳 2)格式化的时间字符串...
    TENG书阅读 3,043评论 0 0
  • Lesson_8 【8】对序列的文件操作:泡菜(pickle) 文件的写入只能写入普通的字符,对于list、tup...
    甜西瓜不太甜阅读 3,836评论 0 1
  • 1、os 模块 OS 模块(operating system),意为操作系统,是 python 处理文件系统的常用...
    焰火青春阅读 3,803评论 0 0
  • 在Python中,与时间处理有关的模块就包括:time,datetime以及calendar。这篇文章,主要讲解t...
    linco159阅读 3,647评论 0 0
  • 放下手机,去做你该做的,因为时间不等人,过了这个村,就没有这个店了,知道吗?明白吗?你想通了吗? 放下手机,做你该...
    感悟人生886阅读 1,751评论 0 1

友情链接更多精彩内容