Patrick Stetz
Patrick Stetz

Reputation: 495

Python get total seconds from datetime results in occasional mistakes

I'm trying to follow these answers and get the elapsed seconds since Jan 1st 1970 for each element in my array (my_times). I'm then using these values to find the time intervals between each consecutive time. Either approach I take seems to give the wrong answer for at least one pair of times.

Mark Byers answer

To get the seconds since Jan 1st 1970, he suggested to try:

time.mktime(my_time.timetuple())

However this does not seem to work for times "2017-11-05 01:46:00+00" and "2017-11-05 01:47:00+00".

When I run the below code, it says the values are separated by 3660.0 seconds instead of 60.0 seconds

from datetime import datetime
import time

my_time1 = datetime.strptime("2017-11-05 01:46:00+00", "%Y-%m-%d %H:%M:%S+%f")
my_time2 = datetime.strptime("2017-11-05 01:47:00+00", "%Y-%m-%d %H:%M:%S+%f")
time.mktime(my_time2.timetuple()) - time.mktime(my_time1.timetuple())

Andrzej Pronobis' answer

To get the seconds since Jan 1st 1970, he suggested to try:

my_time.timestamp()

This fixed the two earlier times however it no longer works for times "2017-11-05 01:59:00+00" and "2017-11-05 02:00:00+00". The same issue appears, I get 3660.0 seconds instead of 60.0 seconds

from datetime import datetime

my_time1 = datetime.strptime("2017-11-05 01:59:00+00", "%Y-%m-%d %H:%M:%S+%f")
my_time2 = datetime.strptime("2017-11-05 02:00:00+00", "%Y-%m-%d %H:%M:%S+%f")
my_time2.timestamp() - my_time1.timestamp()

I'd like to know if I'm doing anything wrong? Also is there a better way to find all consecutive time intervals when the datetime is given as a String?


Edit:

Thank you John, that fixed the problem. Oddly, changing the format from +%f to %z still ran into the same issue.

What did work was running sudo ln -sf /usr/share/zoneinfo/UTC /etc/localtime (changes my computer's time to UTC) and then evaluating all the times

Upvotes: 1

Views: 647

Answers (1)

John Zwinck
John Zwinck

Reputation: 249153

This is a case of "garbage in, garbage out." Here:

datetime.strptime("2017-11-05 01:59:00+00", "%Y-%m-%d %H:%M:%S+%f")

You probably think that +00 on the end means "UTC time", but the %f format specifier means "fractional seconds."

In any case, you're apparently running on a system where the time zone is set to one with daylight saving time part of the year. 2 AM happens twice on the DST changeover date in November, so your code is working as written (it's ambiguous, basically).

Put another way: your issue is not that you're computing time deltas incorrectly. Your issue is that you are loading the times from strings incorrectly (or ambiguously).

Upvotes: 3

Related Questions