Py学习  »  Python

如何从Python中的datetime对象计算年份分数?

IronMarshal • 4 年前 • 202 次点击  

我有两个约会 datetime yearfrac 功能)。

使用 relativedelta

start_date = dt.datetime(2010, 12, 31)
end_date = dt.datetime(2019, 5, 16);
delta = relativedelta(end_date, start_date);
print(delta)

这是我得到的输出:

相对负债(年=+8,月=+4,天=+16)

8.38

如果我使用以下代码:

delta = (end_date - start_date)/365.25
print(delta)

我得到的输出:

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53122
 
202 次点击  
文章 [ 2 ]  |  最新文章 4 年前
Matthew Cole
Reply   •   1 楼
Matthew Cole    4 年前

有件事要记住 datetime.datetime datetime.timedelta 反对。以及 对象定义了除法运算符,因此可以得到 timedelta

import datetime as dt

start_date = dt.datetime(2010, 12, 31)
end_date = dt.datetime(2019, 5, 16)
print(round((end_date-start_date)/dt.timedelta(365,0,0,0),2)) #8.38
print(round((end_date-start_date)/dt.timedelta(365,5,49,12),2)) #8.38
therealJoeT
Reply   •   2 楼
therealJoeT    4 年前

我刚算出8+(月*30+)天/365=8.3726。假设每个月30天,一年365天。不太精确,但可以放在一条线上。当你除以365.25这个数字时,你得到了什么?必须有多精确?

如果你需要绝对精确,我只需要:

from datetime import date

d0 = date(2010, 12, 31)
d1 = date(2019, 5, 16)
delta = d1 - d0
delta_fraction = delta.days/365.25
print(delta_fraction)
# Output: 8.72348

编辑