为了账号安全,请及时绑定邮箱和手机立即绑定

如何在python中找到两个日期时间对象之间的时差?

如何在python中找到两个日期时间对象之间的时差?

弑天下 2019-07-29 17:16:47
如何在python中找到两个日期时间对象之间的时差?如何判断两个datetime对象之间的分钟时差?
查看完整描述

3 回答

?
叮当猫咪

TA贡献1776条经验 获得超12个赞

>>> import datetime

>>> a = datetime.datetime.now()

>>> b = datetime.datetime.now()

>>> c = b - a

datetime.timedelta(0, 8, 562000)

>>> divmod(c.days * 86400 + c.seconds, 60)

(0, 8)      # 0 minutes, 8 seconds


查看完整回答
反对 回复 2019-07-29
?
心有法竹

TA贡献1866条经验 获得超5个赞

使用datetime示例


>>> from datetime import datetime

>>> then = datetime(2012, 3, 5, 23, 8, 15)        # Random date in the past

>>> now  = datetime.now()                         # Now

>>> duration = now - then                         # For build-in functions

>>> duration_in_s = duration.total_seconds()      # Total number of seconds between dates

持续时间多年


>>> years = divmod(duration_in_s, 31556926)[0]    # Seconds in a year=31556926.

持续时间(天)


>>> days  = duration.days                         # Build-in datetime function

>>> days  = divmod(duration_in_s, 86400)[0]       # Seconds in a day = 86400

持续时间(小时)


>>> hours = divmod(duration_in_s, 3600)[0]        # Seconds in an hour = 3600

持续时间(分钟)


>>> minutes = divmod(duration_in_s, 60)[0]        # Seconds in a minute = 60

持续时间(秒)


>>> seconds = duration.seconds                    # Build-in datetime function

>>> seconds = duration_in_s

持续时间,以微秒为单位


>>> microseconds = duration.microseconds          # Build-in datetime function  

两个日期之间的总持续时间


>>> days    = divmod(duration_in_s, 86400)        # Get days (without [0]!)

>>> hours   = divmod(days[1], 3600)               # Use remainder of days to calc hours

>>> minutes = divmod(hours[1], 60)                # Use remainder of hours to calc minutes

>>> seconds = divmod(minutes[1], 1)               # Use remainder of minutes to calc seconds

>>> print("Time between dates: %d days, %d hours, %d minutes and %d seconds" % (days[0], hours[0], minutes[0], seconds[0]))

或者干脆:


>>> print(now - then)


查看完整回答
反对 回复 2019-07-29
  • 3 回答
  • 0 关注
  • 813 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信