python基础——时间(time&datatime)
1.time
import time # 获取当前时间,时间戳 从1970年1月1日0点0分0秒 到此刻的秒数 now = time.time() print(f"{now=}",type(now)) #浮点数 # 获取当前时间,标准时间 年月日,时分秒 now_st = time.localtime(now) print(f"{now_st}",type(now_st)) #时间对象实例time.struct_time # 时间转字符,格式化 now_str = time.strftime("%Y-%m-%d %H:%M:%S", now_st) print(f"{now_str}",type(now_str)) time.sleep(2) # 暂停2秒 # 字符串转时间 #字符转时间 past_st = time.strptime("2022-08-05 21:57:54", "%Y-%m-%d %H:%M:%S") print(f"{past_st}",type(past_st)) #时间对象实例time.struct_time # 时间转时间戳 past = time.mktime(past_st) print(f"{past}",type(past))
>>>
now=1659978197.715609 <class 'float'>
time.struct_time(tm_year=2022, tm_mon=8, tm_mday=9, tm_hour=1, tm_min=3, tm_sec=17, tm_wday=1, tm_yday=221, tm_isdst=0) <class 'time.struct_time'>
2022-08-09 01:03:17 <class 'str'>
time.struct_time(tm_year=2022, tm_mon=8, tm_mday=5, tm_hour=21, tm_min=57, tm_sec=54, tm_wday=4, tm_yday=217, tm_isdst=-1) <class 'time.struct_time'>
1659707874.0 <class 'float'>
2. datetime
import time import datetime now = datetime.datetime.now() # 当前时间,时间d实例对象atetime.datetime print(f"{now=}",type(now)) print(now.year) print(now.month) print(now.day) print(now.hour) print(now.minute) print(now.second) #时间转时间戳 print(now.timestamp(),type(now.timestamp())) # 转为时间戳 time.sleep(1) # 暂停 #时间戳转时间 past = datetime.datetime.fromtimestamp(now.timestamp()) #时间实例对象datetime.datetime print(f"{past}",type(past))
>>>
now=datetime.datetime(2022, 8, 9, 1, 2, 3, 974984) <class 'datetime.datetime'>
2022
8
9
1
2
3
1659978123.974984 <class 'float'>
2022-08-09 01:02:03.974984 <class 'datetime.datetime'>
3.计算时间差
import datetime import time t1 = time.time() # 时间戳 数字 dt1 = datetime.datetime.now() # dt 实例对象 time.sleep(2) t2 = time.time() # 时间戳 数字 dt2 = datetime.datetime.now() # dt 实例对象 print(f"{t2- t1=}") # 差值是数字 print(f"{dt2- dt1=}") # 差值是对象
>>>
t2- t1=2.0110411643981934
dt2- dt1=datetime.timedelta(seconds=2, microseconds=11041