=====字符串、时间戳、时间之间的相互转换=====
import time
import datetime
import random
字符串转换成时间
str_t1 = "2018-11-21 16:10:10"
str_t2 = "2018-11-18 16:10:20"
dt_t1 = datetime.datetime.strptime(str_t1, "%Y-%m-%d %H:%M:%S")
dt_t2 = datetime.datetime.strptime(str_t2, "%Y-%m-%d %H:%M:%S")
时间转字符串
dt_to_str_1 = dt_t1.strftime("%Y-%m-%d %H:%M:%S")
把字符串转换成时间戳
ts_t1 = time.mktime(time.strptime(str_t1, "%Y-%m-%d %H:%M:%S"))
ts_t2 = time.mktime(time.strptime(str_t2, "%Y-%m-%d %H:%M:%S"))
把时间戳转换成字符串
ts_to_str_1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts_t1))
ts_to_str_2 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts_t2))
将datetime转换成时间戳
dt_to_ts_1 = time.mktime(dt_t1.timetuple())
dt_to_ts_2 = time.mktime(dt_t2.timetuple())
计算时间差
delta_day = (dt_t1 - dt_t2).days
delta_sec = (dt_t1 - dt_t2).seconds
delta_totalsec = (dt_t1 - dt_t2).total_seconds() #精确秒数,有别于delta_sec
几天前和几天后的时间
三天前
day_ago = dt_t1 + datetime.timedelta(days = -3)
一周前
week_ago = dt_t1 + datetime.timedelta(weeks = -1)
五天后
day_later = dt_t1 + datetime.timedelta(days = 5)
将时间戳转换成时间元组
"""
时间元组的数据含义
time.struct_time(
tm_year=2018, tm_mon=11, tm_mday=21, tm_hour=16, tm_min=10,
tm_sec=10, tm_wday=2, tm_yday=325, tm_isdst=0)
"""
tuple_t1 = time.localtime(ts_t1)
tuple_t2 = time.localtime(ts_t2)
分别获取时间和日期
time_1 = dt_t1.strftime("%H:%M:%S")
date_1 = dt_t1.strftime("%Y-%m-%d")
=====生成随机时间序列=====
ts_t1 = time.mktime(tuple_t1)
ts_t2 = time.mktime(tuple_t2)
rand_t = []
for i in range(10):
生成一个开始时间戳和结束时间戳之间的随机整数
t = random.randint(ts_t2, ts_t1)
根据时间戳生成时间元组
tuple_t = time.localtime(t)
将时间元组转换成字符串
str_t = time.strftime("%Y-%m-%d %H:%M:%S", tuple_t)
将字符串转换成时间格式
dt_t = datetime.datetime.strptime(str_t, "%Y-%m-%d %H:%M:%S")
rand_t.append(dt_t)