无法找到两个日期时间变量之间的差异

时间:2019-04-28 16:58:08

标签: python datetime

我正在尝试在python中找到两个datetime变量的区别

我尝试使用两个变量的直接差,尝试使用strptime()函数

from datetime import datetime
time = datetime.now()
#timestamp variable gets time value from database
print "time 1:" + str(timestamp)
print "time 2:" + str(time)
#diff = timestamp-time; #already tried
#diff = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S") - datetime.strtime(time, "%Y-%m-%d %H:%M:%S") # already tried
diff= datetime.datetime(timestamp, "%Y-%m-%d %H:%M:%S") - datetime.datetime(time, "%Y-%m-%d %H:%M:%S")
print diff

期望以秒为单位的输出,实际结果是错误类型

1 个答案:

答案 0 :(得分:3)

您可以在total_seconds()上使用datetime.timedelta以秒为单位求差:

diff = (timestamp-time).total_seconds()

代码

from datetime import datetime

timestamp = '2019-04-01 07:12:00'
time = '2019-04-01 07:11:0'

print("time 1:" + str(timestamp))
print("time 2:" + str(time))

timestamp = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
time = datetime.strptime(time, "%Y-%m-%d %H:%M:%S")

diff = (timestamp-time).total_seconds()

print(diff)
# 60.0