我正在像这样计算两个时间值之间的差:
current_time = '2019-08-22T17:58:28'
alert_time = '2019-08-22T16:58:28'
diff = datetime.datetime.strptime(current_time, datetimeFormat) - datetime.datetime.strptime(alert_time, datetimeFormat)
diff
datetime.timedelta(0, 3600)
print(diff)
1:00:00
所以这可以按预期工作,但是我需要将diff
变量添加到字典中,并且我只需要添加数值差,例如3600
那么如何将diff
格式化为3600
?
我知道我可以做str(diff)
并返回1:00:00
,但我希望该值以秒为单位
答案 0 :(得分:1)
执行以下操作:
get()
输出:
import datetime
current_time = '2019-08-22T17:58:28'
alert_time = '2019-08-22T16:58:28'
datetimeFormat = '%Y-%m-%dT%H:%M:%S'
diff = datetime.datetime.strptime(current_time, datetimeFormat) - datetime.datetime.strptime(
alert_time, datetimeFormat
)
d = diff.total_seconds()
print(d)
看到@felixkagota的答案后。我做了一个快速的谷歌,以找出3600.0
和timedelta.seconds
之间的区别。基本上timedelta.to_seconds()
返回整数,即:它不占几分之一秒。例如:
timedelta.seconds
给予:
import datetime
current_time = '2019-08-22T17:58:28:000000'
alert_time = '2019-08-22T16:58:28:123456'
datetimeFormat = '%Y-%m-%dT%H:%M:%S:%f'
diff = datetime.datetime.strptime(current_time, datetimeFormat) - datetime.datetime.strptime(
alert_time, datetimeFormat
)
print(diff.total_seconds())
print(diff.seconds)
答案 1 :(得分:1)
只差一秒。 Timedelta类包含一个seconds属性,该属性以秒为单位返回timedelta值。