gpt4 book ai didi

python datetime.timedelta 成一个列表

转载 作者:行者123 更新时间:2023-12-04 08:50:38 28 4
gpt4 key购买 nike

我有一个 时间值(value)存放在一个名为 newTime 的变量中.
当打印 newTime它给了我这样的结果 newTime = 0:07:00女巫很棒,因为我喜欢那样。
但是当保存 newTimelist结果值变为 datetime.timedelta(seconds=14820)所以任何帮助以 newTime 的方式保存它的列表有一个值 0:07:00这是我的代码:

list = []
date_now = datetime.now()
now = date_now.strftime("%H:%M")
timeB = datetime.strptime(now, "%H:%M")

for temp in temps_arret_aller:
timeA = datetime.strptime(temp[0], "%H:%M")

newTime = timeA - timeB

print(newtime) # 0:07:00
list.append(newtime)

print(list) # datetime.timedelta(seconds=420)

最佳答案

就像我在评论中写的那样,您必须转换 datetime.timedelta 对象:

import datetime

new_time = datetime.time(minute=7)
print(new_time)
# >> 00:07:00
print(type(new_time))
# >> <class 'datetime.time'>

new_time_list: list = [new_time]
print(new_time_list)
# >> ['00:07:00']
print(type(new_time_list[0]))
# >> <class 'datetime.time'>

new_time_list: list = [str(new_time)]
print(new_time_list)
# >> ['00:07:00']
print(type(new_time_list[0]))
# >> <class 'str'>

new_time_list = [new_time.isoformat()]
print(new_time_list)
# >> ['00:07:00']
print(type(new_time_list[0]))
# >> <class 'str'>
对于您的代码:
from datetime import datetime

list_dt_obj: list = []
list_str: list = []
date_now = datetime.now()
now = date_now.strftime("%H:%M")
timeB = datetime.strptime(now, "%H:%M")

temps_arret_aller = ["00:00", "00:07", "00:14", "00:21"]

for temp in temps_arret_aller:
timeA = datetime.strptime(temp, "%H:%M")

newTime = timeA - timeB

print(newTime) # print datetime.timedelta obj: output as string
list_dt_obj.append(newTime) # add datetime.timedelta obj
list_str.append(str(newTime)) # toString

print(list_dt_obj) # list of datetime.timedelta obj
print(list_str) # list of strings

# output:
# -1 day, 10:19:00
# -1 day, 10:26:00
# -1 day, 10:33:00
# -1 day, 10:40:00
# [datetime.timedelta(-1, 37140), datetime.timedelta(-1, 37560), datetime.timedelta(-1, 37980), datetime.timedelta(-1, 38400)]
# ['-1 day, 10:19:00', '-1 day, 10:26:00', '-1 day, 10:33:00', '-1 day, 10:40:00']

关于python datetime.timedelta 成一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64118482/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com