python time list, timestamp list conversion

Convert list of times to list of timestamps

To convert a list of times to a list of timestamps, you can use the datetime module and the time module in Python.
Suppose there is a time list 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'
]

We can use datetime.strptime() to convert a time string to a datetime.datetime object, and then use datetime.timestamp() to convert a datetime object to a timestamp:

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)

output:

[1651165200.0, 1651165500.0, 1651165800.0, 1651166100.0, 1651166400.0]

convert list of timestamps to list of times

To convert a list of timestamps to a list of times, use time.localtime() to convert the timestamps to a time.struct_time object, and time.strftime() to convert the time.struct_time object to a time string:


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)

output:

['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']

actual case

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

insert image description here

Guess you like

Origin blog.csdn.net/weixin_44161444/article/details/130393705