Python中如何计算时间差?

2023-06-0508:30:56编程语言入门到精通Comments919 views字数 925阅读模式

Python语言中,常用的时间模块主要分为两种,分别是:time模块和datetime模块。datetime模块是Python处理时间和日期的标准库,与time模块一样,无需下载,在使用前直接导入即可。那么Python中如何计算时间差?具体请看下文。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/44460.html

Python中如何计算时间差?文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/44460.html

  Python计算时间差的方法:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/44460.html

Python求时间差主要是用的datetime包,包括同一天情形下的时间差和不同天情形下的时间差。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/44460.html

from datetime import datetime, date文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/44460.html

1、同一天情形下的时间差seconds,分钟由秒数除以60即可文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/44460.html

#计算时间差的分钟数# 同一天的时间差time_1 = '2023-04-17 17:30:30'time_2 = '2023-04-17 18:30:30'time_1_struct = (time_1, "%Y-%m-%d %H:%M:%S")time_2_struct = (time_2, "%Y-%m-%d %H:%M:%S")seconds = (time_2_struct - time_1_struct).secondsprint('同一天的秒数为:')print(seconds)

2、不同天情形下的时间差,也可计算同一天情形下的时间差,total_seconds文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/44460.html

# 不同天的时间差time_1 = '2023-04-17 17:30:30'time_1 = '2023-04-18 16:30:30'time_1_struct = (time_1, "%Y-%m-%d %H:%M:%S")time_2_struct = (time_2, "%Y-%m-%d %H:%M:%S")# 来获取时间差中的秒数。注意,seconds获得的秒只是时间差中的小时、分钟和秒部分,没有包含天数差,total_seconds包含天数差# 所以total_seconds两种情况都是可以用的total_seconds = (time_2_struct - time_1_struct).total_seconds()print('不同天的秒数为:')print(int(total_seconds))min_sub = total_seconds / 60print('不同天的分钟数为:')print(int(min_sub))
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/44460.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/44460.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定