python时间列表 、时间戳列表相互转换 | 您所在的位置:网站首页 › 将时间戳转为时间 › python时间列表 、时间戳列表相互转换 |
时间列表转换为时间戳列表
要将时间列表转换为时间戳列表,可以使用Python中的datetime模块和time模块。 假设有一个时间列表time_list: import datetime time_list = [ '2022-04-28 10:00:00', '2022-04-28 10:05:00', '2022-04-28 10:10:00', '2022-04-28 10:15:00', '2022-04-28 10:20:00' ]我们可以使用datetime.strptime()将时间字符串转换为datetime.datetime对象,再使用datetime.timestamp()将datetime对象转换为时间戳: import datetime time_list = [ '2022-04-28 10:00:00', '2022-04-28 10:05:00', '2022-04-28 10:10:00', '2022-04-28 10:15:00', '2022-04-28 10:20:00' ] timestamp_list = [] for time_str in time_list: dt_obj = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S') timestamp = dt_obj.timestamp() timestamp_list.append(timestamp) print(timestamp_list)输出: [1651165200.0, 1651165500.0, 1651165800.0, 1651166100.0, 1651166400.0] 时间戳列表转换为时间列表要将时间戳列表转换为时间列表,可以使用time.localtime()将时间戳转换为time.struct_time对象,再使用time.strftime()将time.struct_time对象转换为时间字符串: import time timestamp_list = [ 1651165200.0, 1651165500.0, 1651165800.0, 1651166100.0, 1651166400.0 ] time_list = [] for timestamp in timestamp_list: time_struct = time.localtime(timestamp) time_str = time.strftime('%Y-%m-%d %H:%M:%S', time_struct) time_list.append(time_str) print(time_list)输出: ['2022-04-28 10:00:00', '2022-04-28 10:05:00', '2022-04-28 10:10:00', '2022-04-28 10:15:00', '2022-04-28 10:20:00'] 实际案例 timeArray01 = time.strptime(data["Time"][0], "%Y-%m-%d %H:%M:%S") #转换成时间戳 timestamp01 = time.mktime(timeArray01) list_of_times = [] for dataTime in data["Time"]: #转换成时间数组 timeArray = time.strptime(dataTime, "%Y-%m-%d %H:%M:%S") #转换成时间戳 timestamp = time.mktime(timeArray) timestamp = timestamp - timestamp01 # timestamp=timestamp/60/60 list_of_times.append(timestamp) list_of_times |
CopyRight 2018-2019 实验室设备网 版权所有 |