获取当前时间戳
import time
result = time.time()
print(result)
years = result / (24 * 60 * 60 * 365) +1970
print(years)
result = time.localtime()
print(result)
获取格式化的时间
# 获取格式化的时间
# 秒 -> 可读时间
# import time
# time.ctime([seconds])
# seconds
# 可选的时间戳
# 默认当前时间戳
t = time.time()
result = time.ctime(t)
print(result)
# 时间元组 -> 可读时间
# import time
# time.asctime([p_tuple])
# p_tuple
# 可选的时间元组
# 默认当前时间元组
time_tuple = time.localtime()
result = time.asctime(time_tuple)
print(result)
格式化日期字符串 <--> 时间戳
# 时间元组 -> 格式化日期
# time.strftime(格式字符串, 时间元组)
# 例如
# time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# 2017-09-02 17:21:00
result = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(result)
# 格式化日期 -> 时间元组
# time.strptime(日期字符串, 格式符字符串)
# time.mktime(时间元组)
# 例如
# time.mktime(time.strptime("2017-09-02 17:21:00", "%Y-%m-%d %H:%M:%S"))
# 1504344060.0
pt = time.strptime("2023-07-19 10:11:23", "%Y-%m-%d %H:%M:%S")
print(pt)
t = time.mktime(pt)
print(t)
获取当前CPU时间
# 获取当前CPU时间
# time.clock( )
# 浮点数的秒数
# 可用来统计一段程序代码的执行耗时
# 注意在python3.8中 time.clock()用time.perf_counter()代替
start = time.perf_counter()
for i in range(0, 10000):
print(i)
end = time.perf_counter()
print(end - start)
休眠n秒
while True :
result = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(result)
time.sleep(1)
获取当天时间及当前的年月日时分
# 获取当天日期
import datetime
t = datetime.datetime.now()
print(datetime.datetime.today())
# 单独获取当前的年月日时分秒
print(type(t))
print(t.year)
print(t.month)
print(t.day)
print(t.hour)
print(t.month)
print(t.second)
# 获取两个日期时间的时间差
import datetime
first = datetime.datetime(2017, 9, 1, 12, 0, 0)
second = datetime.datetime(2017, 9, 2, 12, 0, 0)
result = second - first
print(type(result))
print(result.total_seconds())