How to turn a total number of seconds into years, months, days, minutes and seconds in Python

1 Answer

0 votes
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

def seconds_to_years_months_days_hours_minutes_seconds(seconds):
    start = datetime(2000, 1, 1)
    end = start + timedelta(seconds=seconds)
    diff = relativedelta(end, start)

    return {
        "years": diff.years,
        "months": diff.months,
        "days": diff.days,
        "hours": diff.hours,
        "minutes": diff.minutes,
        "seconds": diff.seconds,
    }

print(seconds_to_years_months_days_hours_minutes_seconds(100_000_000))


'''
run:

{'years': 3, 'months': 2, 'days': 2, 'hours': 9, 'minutes': 46, 'seconds': 40}

'''

 



answered Jan 20 by avibootz

Related questions

...