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


    专栏导读

    • 🌸 欢迎来到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来保留两位小数
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 输出

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

    方法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.")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    总结

    • 希望对初学者有帮助

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

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

    • 求个 🤞 关注 🤞

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

    • 求个 ❤️ 喜欢 ❤️

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

    • 求个 👍 收藏 👍

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

  • 相关阅读:
    SparkStreaming介绍
    Python 多线程 DNS 搜索性能优化
    Mybatis-Plus的CURD实操
    DP4361国产六通道立体声D/A音频转换器芯片替代CS4361
    zabbix监控项
    @Component与@Configuration区别
    Flutter 3.24 更新详解
    4-egg-TS-通用后端管理注册系统-邮箱验证码
    一对一交友App开发指南:从概念到上线的完整路线图
    [洛谷]P2313 [HNOI2005] 汤姆的游戏(模拟)
  • 原文地址:https://blog.csdn.net/weixin_42636075/article/details/138152080