M
M
Max Payne2017-01-22 02:50:13
Python
Max Payne, 2017-01-22 02:50:13

How to correctly calculate time between datetime dates?

I have the following date, for example: 2006-10-01 (yyyy-mm-dd).
I need to calculate the number of years, months and days between a given date and the current one.
I tried many options, but for some reason datetime does not take into account leap years.
Here is an example of my code:

date = "2006-09-23"
date_object = datetime.datetime.strptime(date, "%Y-%m-%d")
delta = datetime.datetime.now() + datetime.timedelta(seconds=-date_object.timestamp()
return 'Аккаунт зарегистрирован: ' + date + '\n' + str(int(delta.strftime('%Y')) - 1970) + ' лет, ' + str(int(delta.strftime('%m')) - 1) + ' месяцев, ' + str(int(delta.strftime('%d')) - 1) + ' дней.'

If there was one leap year between the dates, I get one extra day in the calculation, two leap years - two extra days.
That is, in fact, at the current moment 10 years, 3 months, 29 days have passed between the dates, however, my program returns that 10 years, 4 months, 1 day have passed between the dates. It works correctly only if there were no leap years between the dates.
How to solve this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilyas, 2017-01-22
@id2669099

Here they claim the existence of the calendar module , which takes into account leap years

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question