使减法成为可能:'日期时间.time'和'日期时间。日期时间'

2024-04-20 13:01:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我是萨利赫,我在学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'

谢谢你。你知道吗


Tags: pyfordatetimedatetimeline时间days
2条回答
import datetime
import math

currentDate=datetime.date.today()
currentTime=datetime.datetime.now()

UserInput1=input("What is the deadline for your project? mm/dd/yyyy  ")
deadLine=datetime.datetime.strptime(UserInput1, "%m/%d/%Y").date()

UserInput2=input("Please insert the time hh/mm/ss  ")
deadTime=datetime.datetime.strptime(UserInput2, "%H/%M/%S").time()


daysLeft= deadLine-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)

deadLine=datetime.datetime.combine(deadLine,deadTime)
timeLeft=deadLine-currentTime
print(timeLeft)

你需要把你的date和你的time变成datetime。你知道吗

deadline = datetime.datetime.combine(deadLineDate, deadlineTime)
timeLeft = deadline - currentTime

产生错误的原因是,从time中减去date实际上没有多大意义。e、 什么是“1月29日下午4点-星期五?”。你知道吗

相关问题 更多 >