目录python
python的时间模块函数
一、时间戳 (time.time()
)rest
print(time.time()) #1573885583.36139
二、获取格式化时间 (time.strftime()
)code
print(time.strftime('%Y-%m-%d %H:%M:%S')) #%X == %H:%M:%S 2019-11-16 14:27:43
三、获取时间对象 (time.locatime()
)orm
t = time.localtime() print(t.tm_year) print(t.tm_mon) print(t.tm_mday) 2019 11 16
strftime()不带参数默认当前时间 print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) #2019-11-16 14:39:43
print( time.strptime('2019-01-01', '%Y-%m-%d')) #time.struct_time(tm_year=2019, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=1, tm_isdst=-1)
perf_counter()
sleep()
函数 | 描述 |
---|---|
perf_counter() |
返回一个CPU几遍的精确时间计数值,单位为秒;因为这个计数值起点不肯定,连续调用差值才有意义 |
start_time = time.perf_counter() #精确开始时间 end_time = time.perf_counter() #精确结束时间 restime = end_time - start_time
函数 | 描述 |
---|---|
sleep(s) |
s拟休眠的时间,单位是秒,能够是浮点数 |
主要用于日期时间计算对象
获取当前年月日字符串
import datetime print(datetime.date.today()) #2019-11-16
获取当前年月日时分秒it
import datetime print(datetime.datetime.today()) #2019-11-16 14:49:02.755061
t = datetime.datetime.today() print(t.year) print(t.month) #2019 #11 print(datetime.datetime.now()) #北京时间 print(datetime.datetime.utcnow()) #格林威治 #2019-11-16 14:52:58.447166 #2019-11-16 06:52:58.447166
日期时间的计算table
日期时间 = 日期时间 “+” or “-” 时间对象class
时间对象 = 日期时间 “+” or “-” 日期时间
datetime.timedelta(day=7)
时间对象
current_time = datetime.datetime.now() #获取如今时间 print(current_time) time_obj = datetime.timedelta(days=7) #时间对象,获取7天时间 print(time_obj) later_time = current_time + time_obj #获取7天后的时间,加上7天 print(later_time) before = current_time - time_obj #获取7天以前的时间,减上7天 print(before)