How to Convert HH:MM:SS Strings to Seconds in Python – Multiple Approaches Explained
This article explores several Python techniques—including the time, datetime, and dateutil modules, as well as pure arithmetic and NumPy—to reliably transform a "HH:MM:SS" string into the total number of seconds, while addressing timezone and year‑offset nuances.
How to Convert HH:MM:SS Strings to Seconds in Python
This piece is part of a series that shares interesting technical insights gathered from various sources, aiming to spark curiosity and broaden thinking during study breaks.
Problem Statement
Given a time string such as "20:15:31", we need to compute the total number of seconds (20 × 3600 + 15 × 60 + 31 = 72931 seconds).
Using the time Module
The built‑in time module can parse the string into a struct_time object, but the default year is 1900, which is earlier than the Unix epoch.
import time
time.strptime('20:15:31', '%H:%M:%S')[:6]
# (1900, 1, 1, 20, 15, 31)Converting this struct to a timestamp with time.mktime fails because the year is before 1970. Adding a dummy year (1970) and compensating for the local timezone offset yields the correct result.
import time
t = time.strptime('1970 20:15:31', '%Y %H:%M:%S')
seconds = time.mktime(t) - time.timezone
# 72931.0Using the datetime Module
The datetime module behaves similarly, returning a datetime with year 1900.
from datetime import datetime
dt = datetime.strptime('20:15:31', '%H:%M:%S')
# datetime.datetime(1900, 1, 1, 20, 15, 31)Because the year is before the epoch, we can compute the difference from a reference date (e.g., 1900‑01‑01) and read the seconds attribute.
from datetime import datetime
delta = datetime.strptime('20:15:31', '%H:%M:%S') - datetime(1900, 1, 1)
seconds = delta.seconds # 72931Using python-dateutil
The third‑party python-dateutil parser attaches the current date to the time, allowing direct subtraction.
from dateutil.parser import parse
seconds = (parse('20:15:31') - parse('0:0:0')).seconds
# 72931Direct Arithmetic Calculation
By splitting the string on ':' and multiplying by the appropriate factors, we can compute the total seconds without any library.
seconds = sum(map(lambda x, y: x * y, map(int, '20:15:31'.split(':'), [3600, 60, 1]))
# 72931NumPy can perform the same operation more compactly.
import numpy as np
seconds = np.sum(np.array(['20', '15', '31'], dtype='int32') * [3600, 60, 1])
# 72931Conclusion
The article demonstrates several ways to turn an "HH:MM:SS" string into seconds in Python, highlighting pitfalls such as year offsets and timezone adjustments, while also showing that a simple arithmetic approach can be the most straightforward solution.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
