- 获取当前时间戳
>>> import time
>>> num = time.time() # 当前时间戳, 7位浮点
>>> type(num)
<class 'float'>
>>> num
1623302086.1892786
- 数字 转 时间
>>> t = time.localtime(num) # 数字 转 时间
>>> type(t)
<class 'time.struct_time'>
>>> t
time.struct_time(tm_year=2021, tm_mon=6, tm_mday=10, tm_hour=13, tm_min=14, tm_sec=46, tm_wday=3, tm_yday=161, tm_isdst=0)
- 时间 转 字符串
>>> dt = time.strftime("%Y-%m-%d %H:%M:%S", t) # 记忆 str from time
>>> dt
'2021-06-10 13:14:46'
>>> type(dt)
<class 'str'>
- 字符串 转 时间
>>> string = '2021-06-10 13:14:46.123456'
>>> dt1 = time.strptime(string, "%Y-%m-%d %H:%M:%S.%f") # 记忆 str pass to time
>>> dt1
time.struct_time(tm_year=2021, tm_mon=6, tm_mday=10, tm_hour=13, tm_min=14, tm_sec=46, tm_wday=3, tm_yday=161, tm_isdst=-1)
>>> type(dt1)
<class 'time.struct_time'>
- 时间 转 浮点 / int
>>> num2 = time.mktime(dt1)
>>> type(num2)
<class 'float'>
>>> num2
1623302086.0
注意:存在 秒级以下 的精度丢失问题
- 日期时间,加减法
求往前 7 天的时间戳
import time
import datetimedef fromTimeStamp(delta_day):print(datetime.datetime.now())day = ((datetime.datetime.now()) + datetime.timedelta(days=delta_day)).strftime("%Y-%m-%d %H:%M:%S.%f")print(day)dt = time.strptime(day, "%Y-%m-%d %H:%M:%S.%f")print(dt)ts = int(time.mktime(dt)*1000)return ts
输出:
fromTimeStamp(-7)2022-06-10 09:44:10.549160
2022-06-03 09:44:10.550160
time.struct_time(tm_year=2022, tm_mon=6, tm_mday=3, tm_hour=9, tm_min=44, tm_sec=10, tm_wday=4, tm_yday=154, tm_isdst=-1)
1654220650000