gpt4 book ai didi

python - 类型错误 : unsupported operand type(s) for -: 'str' and 'str' when passing two dates

转载 作者:太空宇宙 更新时间:2023-11-04 11:12:27 25 4
gpt4 key购买 nike

我正在尝试传递存储为字符串的两个日期值以查找日期范围内的天数

start = 2019-09-01
end = 2019-09-10

我试图将上面的两个变量传递给下面的表达式并得到下面的错误:

date = [start + datetime.timedelta(days=x) for x in range(0, (end - start).days + 1)]

错误:

TypeError: unsupported operand type(s) for -: 'str' and 'str'

更新:

由于错误 raised unexpected: ValueError('unconverted data remains: T00:00:00')

不得不将日期列修改为字符串

最佳答案

假设您的 startend 对象是 strings,您可以执行以下操作:

from datetime import datetime, timedelta

start = "2019-09-01"
end = "2019-09-10"

# Convert the str dates to actual date objects:
start = datetime.strptime(start, "%Y-%m-%d")
end = datetime.strptime(end, "%Y-%m-%d")

date = [start + timedelta(days=x) for x in range(0, (end - start).days + 1)]
print(date)
# [datetime.datetime(2019, 9, 1, 0, 0), datetime.datetime(2019, 9, 2, 0, 0), datetime.datetime(2019, 9, 3, 0, 0), datetime.datetime(2019, 9, 4, 0, 0), datetime.datetime(2019, 9, 5, 0, 0), datetime.datetime(2019, 9, 6, 0, 0), datetime.datetime(2019, 9, 7, 0, 0), datetime.datetime(2019, 9, 8, 0, 0), datetime.datetime(2019, 9, 9, 0, 0), datetime.datetime(2019, 9, 10, 0, 0)]

关于python - 类型错误 : unsupported operand type(s) for -: 'str' and 'str' when passing two dates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57876549/

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