我是萨利赫,我在学Python。Python是我的第一种编程语言。这是我第二天关注youtube视频“从零到英雄”。我不能解决的第一个问题是时间和日期。你知道吗
挑战:
我做了所有这些,但后来我想添加一个额外的功能,它需要输入时间(hh:mm:ss)并打印这个时间减去当前时间。我是这么想的:
import math
import datetime
currentDate = datetime.date.today()
currentTime = datetime.datetime.now()
deadLine = input('Hello, enter the deadline date for your project (mm/dd/yyyy)')
deadLineDate = datetime.datetime.strptime(deadLine, '%m/%d/%Y').date()
deadLineTime = input('insert time')
deadTime = datetime.datetime.strptime(deadLineTime, '%H:%M:%S').time()
print(deadTime)
daysLeft = deadLineDate - currentDate
print('%d days left' % daysLeft.days)
weeksLeft = math.floor(daysLeft.days/7)
newDaysLeft = daysLeft .days- 7*(math.floor(daysLeft.days/7))
print('You have %d weeks' % weeksLeft, ' and %d days left.' % newDaysLeft)
timeLeft = deadTime - currentTime
print(timeLeft.hours)
输入02/04/2016和15:00时,我得到以下错误:
Hello, enter the deadline date for your project (mm/dd/yyyy)02/04/2016
insert time15:00
15:00:00
5 days left
You have 0 weeks and 5 days left.
Traceback (most recent call last):
File "/Users/PYTHON/challenge04.py", line 31, in <module>
timeLeft = deadTime - currentTime
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.datetime'
>>>
编辑:正如jonatan所说,在没有任何输入的情况下测试代码:
Hello, enter the deadline date for your project (mm/dd/yyyy)
Traceback (most recent call last):
File "/Users/PYTHON/challenge04.py", line 14, in <module>
deadLineDate = datetime.datetime.strptime(deadLine, '%m/%d/%Y').date()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/_strptime.py", line 507, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/_strptime.py", line 344, in _strptime
(data_string, format))
ValueError: time data '' does not match format '%m/%d/%Y'
谢谢你。你知道吗
你需要把你的
date
和你的time
变成datetime
。你知道吗产生错误的原因是,从
time
中减去date
实际上没有多大意义。e、 什么是“1月29日下午4点-星期五?”。你知道吗相关问题 更多 >
编程相关推荐