0

I have two dates defines as below

import datetime

     
d1 = datetime.datetime(2695, 7, 28)
d2 = datetime.datetime(4714, 11, 24)

d3 = d2 - d1


print(d3)

while printing it shows 737543 days, 0:00:00. I am wondering how can I show the difference in YYYY-MM-DD, which should be like, 2019-04-04

Thanks

Danan
  • 1
  • 1
  • Does this answer your question? [How do I find the time difference between two datetime objects in python?](https://stackoverflow.com/questions/1345827/how-do-i-find-the-time-difference-between-two-datetime-objects-in-python) – Mushroomator Sep 19 '22 at 19:04
  • Thanks @Mushroomator but how can I get number of months? Thanks so much! – Danan Sep 19 '22 at 19:06
  • 2
    I think this question is ill-formed, as the length of a "month" (or even year) is not well-defined. For example, let's say that the difference is 33 days. How should this be formatted? How about the difference between `2017-01-01` and `2016-01-01`, which is 366 days but also arguably 1 year? – NicholasM Sep 19 '22 at 19:37
  • I suggest you look at the difference between a `date` representing a specific day in the history of time and a `timedelta` representing a duration of time. Even though we use some of the same labels when measuring these things (such as day and year), they are two very different concepts. – Code-Apprentice Sep 19 '22 at 19:41
  • @NicholasM I would argue that the lengths of months and years ARE well defined, but varies from month to month or year to year. But maybe the distinction here is the difference between "the length of each month" vs "the length of a month". In every day parlance, we often round off the length of a month to be 4 weeks or 28 days. For one or two months, this serves well as a rough approximation, but longer than that we get rounding errors. – Code-Apprentice Sep 19 '22 at 19:44
  • The second is pretty much the only unit of time with a fixed duration. Anything larger could consist of a variable number of seconds, if only because of leap seconds. Months are not so much a unit as a haphazardly sized subdivision of a calendar year. – chepner Sep 19 '22 at 19:44

1 Answers1

0

Maybe something like this will work

import datetime

d1 = datetime.datetime(2695, 7, 28)
d2 = datetime.datetime(4714, 11, 24)

d3 = d2 - d1

zero = datetime.datetime(1,1,1)
final_result = zero+d3

print(final_result)     # 2020-04-29 00:00:00

d3 here is timedelta object
zero is datetime object that is set to zero date
then d3 is just added to zero

But maybe there is smarter way with a function created for turning timedelta into datetime.

Dmitriy Neledva
  • 867
  • 4
  • 10