Python计算两个时间的时间差(工作笔记需要自取)

本文介绍了两种在Python中计算时间差的方法,包括使用自定义函数(方法1)和利用datetime模块(方法2)。适合初学者学习办公自动化中的时间处理技巧。
摘要由CSDN通过智能技术生成

专栏导读

  • 🌸 欢迎来到Python办公自动化专栏—Python处理办公问题,解放您的双手

  • 🏳️‍🌈 博客主页:请点击——> 一晌小贪欢的博客主页求关注

  • 👍 该系列文章专栏:请点击——>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)

    # 确保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}小时")  # 使用:.2f来保留两位小数
  • 输出

10:53:3216:57:41 的 时间差为:6.07小时

方法2

from datetime import datetime

t1 = '10:53:32'
t2 = '16:57:41'

# 将时间字符串转换为datetime对象
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.")

总结

  • 希望对初学者有帮助

  • 致力于办公自动化的小小程序员一枚

  • 希望能得到大家的【一个免费关注】!感谢

  • 求个 🤞 关注 🤞

  • 此外还有办公自动化专栏,欢迎大家订阅:Python办公自动化专栏

  • 求个 ❤️ 喜欢 ❤️

  • 此外还有爬虫专栏,欢迎大家订阅:Python爬虫基础专栏

  • 求个 👍 收藏 👍

  • 此外还有Python基础专栏,欢迎大家订阅:Python基础学习专栏

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一晌小贪欢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值