I know I can use relativedelta to calculate difference between two dates in the calendar. However, it doesn't feet my needs.
我知道我可以用relativelta来计算日历上两个日期之间的差值。然而,这并不能满足我的需求。
I must consider 1 year = 365 days and/or 12 months; and 1 month = 30 days.
我必须考虑1年=365天和/或12个月;1个月=30天。
To transform 3 years, 2 months and 20 days into days, all I need is this formula: (365x3)+(30x2)+20
, which is equal to 1175.
However, how can I transform days into years, months and days, considering that the amount of days may or may not be higher than 1 month or 1 year? Is there a method on Python that I can use?
然而,考虑到天数可能高于也可能不高于1个月或1年,我如何将天数转换为年、月和天?Python上有我可以使用的方法吗?
Mathemacally, I could divide 1175 by 365, multiply the decimals of the result by 365, divide the result by 30 and multiply the decimals of the result by 30. But how could I do that in Python?
数学上,我可以用1175除以365,用结果的小数乘以365,用30除以30。但我怎么能在Python中做到这一点呢?
更多回答
Yes, but that would use the calendar (result may vary, depending on the year and the month), I believe.
是的,但我相信这将使用日历(结果可能会有所不同,取决于年份和月份)。
优秀答案推荐
you don't have to multiply the decimals, use modulo %
to find remainder
你不必乘以小数,用模%来求余数
READ MORE ABOUT IT HERE
点击此处阅读更多信息
totalDays = 120
years = totalDays//365
months = (totalDays%365)//30
days = (totalDays%365)%30
print(years,months,days)
0 0 12
更多回答
If I use 4464 days in your code (12y - 02m - 20d), it will return 12 2 24 instead. The result must be very precise, since it'll be used to calculate benefits (like parole) for sentenced people. Could you help me out figuring out what's wrong? This would be exactly what I need, if I get the correct result.
如果我在你的代码中使用4464天(12y-02m-20d),它将返回12-24。结果必须非常精确,因为它将用于计算被判刑者的福利(如假释)。你能帮我弄清楚出了什么问题吗?如果我得到正确的结果,这正是我所需要的。
我是一名优秀的程序员,十分优秀!