Python:日期时间差给出错误的结果

时间:2018-07-13 02:29:44

标签: python datetime python-dateutil

我编写了一个简单的代码来检查两个日期时间戳之间的时差是否超过7天,即604,800秒。

如果以秒为单位的时间超过604,800,则应打印“放松您的时间!”

请在下面找到我的代码:

import time, datetime, sys, os 
start_time = time.time() 
from datetime import datetime, timedelta, date 
from dateutil.parser import *

datetime1="2018-07-13 03:30:00"  
datetime2="2018-07-20 04:30:00" 
datetime2=datetime.strptime(datetime2, "%Y-%m-%d %H:%M:%S").date() # this is to convert it into a datetime object
datetime1=datetime.strptime(datetime1, "%Y-%m-%d %H:%M:%S").date() # this is to convert it into a datetime object

difference1 =(datetime2-datetime1).total_seconds() 
print("the difference in seconds is "+str(difference1)) 
if difference1 > 604800: #if the difference is more than 7 days, relax , else start preparing
  print("Relax you have time!!!") 
else:
  print("You need to start preparing!!!!!")

问题:

仅当我将“ datetime2” 更改为“ 2018-07-21”时,代码才以某种方式计算出以秒计的时间大于604800,这意味着它正在计算四舍五入后的差值-天数而不是秒数,然后将四舍五入的天数简单地转换为秒数,给出错误的答案。

例如,在上面的代码中,由于实际上“ datetime2” “ datetime1” 的距离超过604,800秒(准确地说是608,400秒离开),输出应该是“放松时间!”,但是我们得到了不同的输出。

我为解决这个问题做了什么?

到目前为止,我已经研究了类似的问题:

How do I check the difference, in seconds, between two dates?(由于出现TypeError而对我不起作用:必须为整数(类型为datetime.date))

Time difference in seconds (as a floating point)(这仅解决了很小的时差,并且在用户自己输入时间戳时未捕获到场景)

How to calculate the time interval between two time strings(这是我在代码中所做的,但未按预期工作)

您能在我的代码中提出问题吗?

更新:感谢@Tim Peters指出.date()丢弃了小时,分钟和秒。 我只需要丢弃.date()即可正常工作。

1 个答案:

答案 0 :(得分:0)

在这种情况下,问题是您用datetime.datetime创建了两个strptime对象,并立即将它们截断为datetime.date对象,这些对象没有时间成分(小时,分钟,秒,微秒,tzinfo),因此您将获得两个日历日期,它们恰好相隔7天。

您可以像这样修改原始代码:

from datetime import datetime, timedelta

datetime1 = "2018-07-13 03:30:00"
datetime2 = "2018-07-20 04:30:00"

# The following creates two datetime.datetime objects
datetime2 = datetime.strptime(datetime2, "%Y-%m-%d %H:%M:%S")
datetime1 = datetime.strptime(datetime1, "%Y-%m-%d %H:%M:%S")

difference1 =(datetime2-datetime1).total_seconds() 
print("the difference in seconds is "+str(difference1)) 

# if the difference is more than 7 days, relax , else start preparing
if difference1 > 604800:
  print("Relax you have time!!!") 
else:
  print("You need to start preparing!!!!!")

另外要注意的一点是,datetime.timedelta对象可以直接比较,因此您无需计算秒数,因此可以更改该部分以避免“秒数”计算(并且您的意图更加清晰):

difference1 = datetime2 - datetime1

# if the difference is more than 7 days, relax , else start preparing
if difference1 > timedelta(days=7):

我想象实际上,您并没有像本例中那样从字符串文字构造datetime.datetime对象,但是如果确实如此,我还要注意您也可以直接构造这些文字,因此有了适当的重构,这就是我编写您的示例的方式:

from datetime import datetime, timedelta

# The following creates two datetime.datetime objects
datetime1 = datetime(2018, 7, 13, 3, 30)
datetime2 = datetime(2018, 7, 20, 4, 30)

difference1 = datetime2 - datetime1

# if the difference is more than 7 days, relax , else start preparing
if difference1 > timedelta(days=7):
  print("Relax you have time!!!") 
else:
  print("You need to start preparing!!!!!")