Python计算时差,给予'年、月、日、时、分、秒'中的1

2wnc66cl  于 2023-04-04  发布在  Python
关注(0)|答案(3)|浏览(117)

我想知道'2014-05-06 12:00:56'和'2012-03-06 16:08:22'之间有多少年、月、日、时、分、秒。结果如下:“差额为xxx年xxx月xxx天xxx小时xxx分钟”
例如:

import datetime

a = '2014-05-06 12:00:56'
b = '2013-03-06 16:08:22'

start = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(b, '%Y-%m-%d %H:%M:%S')

diff = start – ends

如果我这样做:

diff.days

它给出了天数的差异。
我还能做些什么?我怎样才能达到我想要的结果?

yvgpqqbh

yvgpqqbh1#

使用dateutil package中的relativedelta。这将考虑闰年和其他怪癖。

import datetime
from dateutil.relativedelta import relativedelta

a = '2014-05-06 12:00:56'
b = '2013-03-06 16:08:22'

start = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(b, '%Y-%m-%d %H:%M:%S')

diff = relativedelta(start, ends)

>>> print "The difference is %d year %d month %d days %d hours %d minutes" % (diff.years, diff.months, diff.days, diff.hours, diff.minutes)
The difference is 1 year 1 month 29 days 19 hours 52 minutes

您可能需要添加一些逻辑来打印,例如“2 years”而不是“2 year”。

eaf3rand

eaf3rand2#

diff是一个timedelta示例。
对于python2,请参见:https://docs.python.org/2/library/datetime.html#timedelta-objects
对于Python 3,请参阅:https://docs.python.org/3/library/datetime.html#timedelta-objects
来自文档:
timdelta示例属性(只读):

  • 微秒

timdelta示例方法:

  • 总秒数()

timdelta类属性为:

  • 最小
  • 最大
  • 解析度

您可以使用daysseconds示例属性来计算所需的内容。
例如:

import datetime

a = '2014-05-06 12:00:56'
b = '2013-03-06 16:08:22'

start = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(b, '%Y-%m-%d %H:%M:%S')

diff = start - ends

hours = int(diff.seconds // (60 * 60))
mins = int((diff.seconds // 60) % 60)
ne5o7dgx

ne5o7dgx3#

要计算时间戳之间的差值:

from time import time

def timestamp_from_seconds(seconds):
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    days, hours = divmod(hours, 24)
    return days, hours, minutes, seconds

print("\n%d days, %d hours, %d minutes, %d seconds" % timestamp_from_seconds(abs(1680375128- time())))

输出:1天19小时19分钟55秒

相关问题