datetime
获取当前时间
from datetime import datetime
t1 = datetime.now()
print(t1, type(t1))
# 2022-05-17 11:26:58.033436
datetime转字符串
t2 = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(t2, type(t2))
# 2022-05-17 11:29:06
字符串转datetime
t3 = datetime.strptime('2022-05-17 11:29:06', '%Y-%m-%d %H:%M:%S')
print(t3, type(t3))
# 2022-05-17 11:29:06
获取精确到秒级的当前时间
t4 = datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')
print(t4, type(t4))
# 2022-05-17 11:32:44
获取时间戳
t5 = datetime.now().timestamp()
print(t5, type(t5))
# 1652758498.971751
获取精确到秒级的时间戳/字符串转时间戳
t6 = datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S').timestamp()
print(t6, type(t6))
# 1652758879.0
time
获取当前时间字符串
import time
t1 = time.localtime()
print(t1, type(t1))
# time.struct_time(tm_year=2022, tm_mon=5, tm_mday=17, tm_hour=13, tm_min=55, tm_sec=49, tm_wday=1, tm_yday=137, tm_isdst=0)
t2 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(t2, type(t2))
# 2022-05-17 13:55:49
int时间戳转时间字符串
time_stamp = 1652767169
t1 = time.localtime(time_stamp)
print(t1, type(t1))
# time.struct_time(tm_year=2022, tm_mon=5, tm_mday=17, tm_hour=13, tm_min=59, tm_sec=29, tm_wday=1, tm_yday=137, tm_isdst=0)
t2 = time.strftime("%Y.%m.%d %H:%M:%S", t1)
print(t2, type(t2))
# 2022.05.17 13:59:29
字符串转时间戳
t2 = time.mktime(time.strptime("2022-05-17 14:38:43", '%Y-%m-%d %H:%M:%S'))
print(t2, type(t2))
# 1652769523.0
获取时间戳
t3 = time.time()
print(t3, type(t3))
# 1652767464.013739
进阶
获取当天凌晨时间戳
import time
from datetime import date
t1 = int(time.mktime(date.today().timetuple()))
print(t1, type(t1))
# 1652716800
获取一分钟后的时间
t2 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()) + 60))
print(t2, type(t2))
# 2022-05-17 14:41:56