timedelta类型转换
timedalte是Python中datetime的一个对象,该对象表示两个时间的差值。
1.计算两个时间相差多少天
import datetime
begin = datetime.datetime.strptime('2021-3-1 18:20:20', '%Y-%m-%d %H:%M:%S')
end = datetime.datetime.strptime('2021-3-2 18:20:20', '%Y-%m-%d %H:%M:%S')
diff = end - begin
print("两个时间相差{0}天".format(diff.days))
# 输出为 两个时间相差1天
2.计算两个时间相差多少秒
begin = datetime.datetime.strptime('2021-3-1 18:20:20', '%Y-%m-%d %H:%M:%S')
end = datetime.datetime.strptime('2021-3-1 20:20:20', '%Y-%m-%d %H:%M:%S')
diff = end - begin
# 输出为 两个时间相差7200秒
print("两个时间相差{0}秒".format(diff.seconds))
# 输出为 两个时间相差120分钟
print("两个时间相差{0}分钟".format(diff.seconds/60))
# 输出为 两个时间相差2小时
print("两个时间相差{0}小时".format(diff.seconds/3600))