您好,欢迎来到化拓教育网。
搜索
您的当前位置:首页python求时间差

python求时间差

来源:化拓教育网
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).secondsprint('同⼀天的秒数为:')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 / 60print('不同天的分钟数为:')print(int(min_sub))

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.seconds/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)

参考:

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo9.cn 版权所有

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务