简体   繁体   中英

Converting days into years, months and days

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

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

You can use days%365 to get number of years from days.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM