• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python怎么计算时间差

python 搞代码 4年前 (2022-01-09) 25次浏览 已收录 0个评论

python计算时间差的方法:首先引入datetime包;然后通过“(time_2_struct – time_1_struct)”方式计算出同一天情形下的时间差或者不同天的时间差即可。

本文操作环境:windows7系统、python2.7.14版,DELL G3电脑。

python求时间差

python求时间差主要是用的datetime包,包括同一天情形下的时间差和不同天情形下的时间差。

from datetime import datetime, date

1. 同一天情形下的时间差(秒)seconds ,分钟由秒数除以60即可

#计算时间差的分钟数
# 同一天的时间差
time_1 = '2020-03-02 15:00:00'
time_2 = '2020-03-02 16:00:00'
time_1_struct = datetime.strptime(time_1, "%Y-%m-%d %H:%M:%S")
time_2_struct = datetime.strptime(time_2, "%Y-%m-%d %H:%M:%S")
seconds = (time_2_struct - time_1_struct).seconds
print('同一天的秒数为:')
print(seconds)

2. 不同天情形下的时间差(也可计算同一天情形下的时间差),total_seconds

# 不同天的时间差
time_1 = '2020-03-02 15:00:00'
time_2 = '2020-03-03 16:00:00'
time_1_struct = datetime.strptime(time_1, "%Y-%m-%d %H:%M:%S")
time_2_struct = datetime.strptime(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 / 60
print('不同天的分钟数为:')
print(int(min_sub))

【推荐学习:python视频教程】

3. 只有时间time没有日期时,求时间差先可以加上一个相同的日期,再求时间差,datetime.combine 方法

# 只有时间time没有日期时,求时间差先可以加上一个相同的日期,再求时间差
# date.min能表示的最小日期
# date.max能表示的最大日期
# date.today()返回一个当前日期对象
# datetime.combine:根据所给的date和time创建一个datetime对象
time_sub = datetime.combine(date.min, time_2_struct.time()) - datetime.combine(date.min, time_1_struct.time())
print('----- 与最小日期结合: ------')
print(time_sub.sec<span>本文来源gaodai#ma#com搞*!代#%^码网5</span>onds/60)
time_sub = datetime.combine(date.today(), time_2_struct.time()) - datetime.combine(date.today(), time_1_struct.time())
print('----- 与当天日期结合: ------')
print(time_sub.seconds/60)
print(time_sub.total_seconds()/60)

以上就是python怎么计算时间差的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python怎么计算时间差

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址