Python计算时间差的方法是什么?

  Python语言中,常用的时间模块主要分为两种,分别是:time模块和datetime模块。datetime模块是Python处理时间和日期的标准库,与time模块一样,无需下载,在使用前直接导入即可。那么Python中如何计算时间差?具体请看下文。

  Python计算时间差的方法:

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

  from datetime import datetime, date

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

  #计算时间差的分钟数

  # 同一天的时间差

  time_1 = '2023-04-17 17:30:30'

  time_2 = '2023-04-17 18:30:30'

  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 = '2023-04-17 17:30:30'

  time_1 = '2023-04-18 16:30:30'

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值