python如何计算时间差

python如何计算时间差,第1张

python如何计算时间差

python计算时间差的方法:python求时间差主要是用的datetime包,包括同一天情形下的时间差和不同天情形下的时间差,语法为【from datetime import datetime, date】。

本教程 *** 作环境:windows7系统、python3.9版,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视频教程

以上就是python如何计算时间差的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/681143.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-20
下一篇 2022-04-20

发表评论

登录后才能评论

评论列表(0条)

保存