Eray Erdin
Eray Erdin

Reputation: 3179

Getting 3 Hours Difference After Adding 27 Hours with Timedelta

Imports as below:

from datetime import datetime, timedelta

At first, I get date of the moment as seen:

foo = datetime.now()

And then I get 27 hours later as the following:

bar = foo + timedelta(hours=27)

Now I need to test this out. For this purpose, I use another variable as such:

baz = bar-foo

Now I test the difference between bar and foo:

seconds = baz.seconds
hours = seconds/60/60 # which returns 3.0

I have added 27 hours and got 3 hours difference between bar and foo.

What's the cause? Thanks in advance.

Environment

Upvotes: 2

Views: 49

Answers (1)

jpp
jpp

Reputation: 164773

Checking just the seconds attribute of a timedelta object is insufficient.

As per the timedelta documentation:

Only days, seconds and microseconds are stored internally.

Consider these components in turn:

days = baz.days
seconds = baz.seconds
microsecs = baz.microseconds

print(days, seconds, microsecs, sep=', ')
1, 10800, 0

You will need to add these together separately to get your total timedelta. If your aim is to extract the total number of seconds, you can use the total_seconds method:

totalsecs = baz.total_seconds()  # 97200.0
assert totalsecs / 60 / 60 == 27  # check we have 27 hours

Upvotes: 3

Related Questions