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

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值