Subtracting Dates With Python

Subtracting Dates With Python

from datetime import datetime

birthday = datetime(1988, 2, 19, 12, 0, 0)
diff = datetime.now() - birthday
print diff
# 8954 days, 7:03:45.765329

Use UTC time otherwise age in seconds can go backwards during DST transition:

from datetime import datetime

born = datetime(1981, 12, 2) # provide UTC time
age = datetime.utcnow() - born
print(age.total_seconds())

You also cant use local time if your program runs on a computer that is in a different place (timezone) from where a person was born or if the time rules had changed in this place since birthday. It might introduce several hours error.

If you want to take into account leap seconds then the task becomes almost impossible.

Subtracting Dates With Python

When substracting two datetime objects you will get a new datetime.timedelta object.

from datetime import datetime
x = datetime.now()
y = datetime.now()
delta = y - x

It will give you the time difference with resolution to microsencods.

For more information take a look at the official documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *