python怎么计算时间差


本文摘自php中文网,作者藏色散人,侵删。

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

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

python求时间差

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

1

from datetime import datetime, date

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

1

2

3

4

5

6

7

8

9

#计算时间差的分钟数

# 同一天的时间差

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)

e1cfe78925dcb65cb401d91cccd3c03.png

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

1

2

3

4

5

6

7

8

9

10

11

12

13

# 不同天的时间差

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))

bc918cc2f56f753024e50b96110831f.png

阅读剩余部分

相关阅读 >>

Python中如何django使用haystack:全文检索的框架的实例讲解

Python怎么读csv文件

%s在Python中是什么意思

Python增加清屏功能方法介绍

Python迭代器定义与简单用法分析

Python中怎么删除列表中的元素

Python 按照固定长度分割字符串的方法

Python中的turtle模块画图两只小羊

Python 33个保留字是什么意思

Python简单地实现一键提取阴阳师原画方法

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...