Converting days into years, months and days
Question:
I know I can use relativedelta to calculate difference between two dates in the calendar. However, it doesn’t feet my needs.
I must consider 1 year = 365 days and/or 12 months; and 1 month = 30 days.
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?
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?
Answers:
you don’t have to multiply the decimals, use modulo %
to find remainder
totalDays = 120
years = totalDays//365
months = (totalDays%365)//30
days = (totalDays%365)%30
print(years,months,days)
0 0 12
days =400
year = days//365
month = (days%365)//30
day = (days%365)%30
print(year,month,day)
1 1 5
I know I can use relativedelta to calculate difference between two dates in the calendar. However, it doesn’t feet my needs.
I must consider 1 year = 365 days and/or 12 months; and 1 month = 30 days.
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?
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?
you don’t have to multiply the decimals, use modulo %
to find remainder
totalDays = 120
years = totalDays//365
months = (totalDays%365)//30
days = (totalDays%365)%30
print(years,months,days)
0 0 12
days =400
year = days//365
month = (days%365)//30
day = (days%365)%30
print(year,month,day)
1 1 5