专栏导读
-
🌸 欢迎来到Python办公自动化专栏—Python处理办公问题,解放您的双手
-
-
-
-
📕 此外还有python基础专栏:请点击——>Python基础学习专栏求订阅
-
文章作者技术和水平有限,如果文中出现错误,希望大家能指正🙏
-
❤️ 欢迎各位佬关注! ❤️
方法1:
def time_to_seconds(time_str):
"""将时间字符串转换为秒数"""
hours, minutes, seconds = map(int, time_str.split(":"))
return hours * 3600 + minutes * 60 + seconds
def time_difference_in_hours(t1, t2):
"""计算两个时间之间的差值(小数小时)"""
seconds_t1 = time_to_seconds(t1)
seconds_t2 = time_to_seconds(t2)
if seconds_t1 > seconds_t2:
seconds_t1, seconds_t2 = seconds_t2, seconds_t1
diff_in_seconds = seconds_t2 - seconds_t1
diff_in_hours = diff_in_seconds / 3600
return diff_in_hours
t1 = '10:53:32'
t2 = '16:57:41'
diff_in_hours = time_difference_in_hours(t1, t2)
print(f"{t1}至{t2} 的 时间差为:{diff_in_hours:.2f}小时")
10:53:32至16:57:41 的 时间差为:6.07小时
方法2
from datetime import datetime
t1 = '10:53:32'
t2 = '16:57:41'
format_str = '%H:%M:%S'
time1 = datetime.strptime(t1, format_str)
time2 = datetime.strptime(t2, format_str)
duration = time2 - time1
hours = duration.seconds // 3600
minutes = (duration.seconds % 3600) // 60
seconds = duration.seconds % 60
print(f"The duration between {t1} and {t2} is {hours} hours, {minutes} minutes, and {seconds} seconds.")
总结
-
希望对初学者有帮助
-
致力于办公自动化的小小程序员一枚
-
希望能得到大家的【一个免费关注】!感谢
-
求个 🤞 关注 🤞
-
-
求个 ❤️ 喜欢 ❤️
-
-
求个 👍 收藏 👍
-