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

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

如何判断两个datetime对象之间的分钟时差?



弑天下
浏览 814回答 3
3回答

叮当猫咪

>>> import datetime>>> a = datetime.datetime.now()>>> b = datetime.datetime.now()>>> c = b - adatetime.timedelta(0, 8, 562000)>>> divmod(c.days * 86400 + c.seconds, 60)(0, 8)      # 0 minutes, 8 seconds

心有法竹

使用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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python