Python datetime calculation goes wrong

from datetime import datetime

print("For people born on these dates:")
bday1 = datetime(day=24, month=8, year=1967, hour=10)
bday2 = datetime(day=16, month=11, year=2001, hour=17, minute=28)
print(bday1)
print(bday2)

print("Twentytwo Day is")
d1 = min(bday1, bday2)
d2 = max(bday1, bday2)
dd = datetime.fromtimestamp((22.0 * datetime.timestamp(d2) - datetime.timestamp(d1)) / 21.0)
print(dd)
print('LibreOffice, Excel and Mathematica show 2003-07-05 02:57:24')
print(datetime.timestamp(d1))
print(datetime.timestamp(datetime(day=1, month=1, year=1970, hour=1)))
print(datetime.timestamp(d2))
# make it correct and check
dd = dd.replace(hour=dd.hour - 1)
print(dd - d1)
print((dd - d2) * 22)

What am I doing wrong in the calculation of the date/time where the age of one is exactly 22 times the age of the other?

It would be helpful if you included the output generated by your program, with annotations showing where you believe the output to be incorrect.

The output is

For people born on these dates:
1967-08-24 10:00:00
2001-11-16 17:28:00
Twentytwo Day is
2003-07-05 03:57:54.285714 <---- one hour difference with correct result
LibreOffice, Excel and Mathematica show 2003-07-05 02:57:24
-74358000.0
0.0
1005928080.0
13098 days, 16:57:54.285714
13098 days, 16:57:54.285708

These last 2 delta’s are identical, but correction was applied before making the differences.

See the datetime.timestamp documentation. Basically it assumes that you want to use localtime for conversion, and that may introduce DST offsets.

There might be a better way to do this, but my first shot is just to amend your program as shown. I’ve added the UTC timezone info to 3 lines.

from datetime import datetime, timezone

print("For people born on these dates:")
bday1 = datetime(day=24, month=8, year=1967, hour=10, tzinfo=timezone.utc)
bday2 = datetime(day=16, month=11, year=2001, hour=17, minute=28, tzinfo=timezone.utc)
print(bday1)
print(bday2)

print("Twentytwo Day is")
d1 = min(bday1, bday2)
d2 = max(bday1, bday2)
dd = datetime.fromtimestamp((22.0 * datetime.timestamp(d2) - datetime.timestamp(d1)) / 21.0, tz=timezone.utc)
print(dd)
print('LibreOffice, Excel and Mathematica show 2003-07-05 02:57:24')
print(datetime.timestamp(d1))
print(datetime.timestamp(datetime(day=1, month=1, year=1970, hour=1)))
print(datetime.timestamp(d2))
# make it correct and check
dd = dd.replace(hour=dd.hour - 1)
print(dd - d1)
print((dd - d2) * 22)
2 Likes

Thank you very much for this clever extension.
Now the calculation is correct!