gpt4 book ai didi

python - 日期时间模块 Python

转载 作者:太空宇宙 更新时间:2023-11-04 09:15:37 26 4
gpt4 key购买 nike

我正在 Python 中试验 Datetime 模块,并决定制作一个程序来计算前后的天数。相关代码:

if bORf == 'f':
howfarforward = input("How far forward would you like to count?: ")
def countforward(howfarfor):
day = datetime.date.today()
day -= howfarfor
print(day)
countback(howfarfor)

我遇到了错误

Traceback (most recent call last):
File "datecount.py", line 11, in <module>
countback(howfarback)
File "datecount.py", line 9, in countback
day -= howfarback
TypeError: unsupported operand type(s) for -=: 'datetime.date' and 'str'

我知道为什么,只是不知道如何解决。我该怎么做?

其余代码:

import datetime
print("Today is", datetime.date.today())
bORf = input("Would you like to count backwards or forwards? (b/f)")
if bORf == 'b':
howfarback = input("How far back would you like to count?: ")
def countback(howfarback):
day = datetime.date.today()
day -= howfarback
print(day)
countback(howfarback)
...

最佳答案

使用datetime.timedelta , 你需要 parse the input to a number :

>>> import datetime
>>> howfarforward = int(input("How far forward would you like to count?: "))
How far forward would you like to count?: 4
>>> day = datetime.date.today()
>>> day = day + datetime.timedelta(days=howfarforward)
>>> day
datetime.date(2012, 3, 18)

关于python - 日期时间模块 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9712937/

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