Python Convert timedelta to int in a dataframe
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
In pandas, converting a timedelta column to integers is mainly a question of unit choice. A duration can become seconds, minutes, hours, or days, and the correct conversion depends on what downstream code expects. Once the unit is explicit, the transformation is simple and vectorized.
Start With a Timedelta Column
A timedelta column often comes from subtracting one timestamp column from another.
At this point, df["delta"] is a pandas timedelta dtype, not an integer column.
Convert to Integer Seconds
The clearest path is .dt.total_seconds(), then a cast after you decide how to handle fractions.
The important design choice is rounding. In some workflows you want round, in others floor, ceil, or truncation.
Convert to Minutes, Hours, or Days
Other units are just scaled versions of total seconds.
For days, dividing by a timedelata is often the most readable:
The point is not that one method is always best. The point is to make the target unit obvious from both the code and the column name.
Handle Missing Values Carefully
If the column contains NaT, a direct cast to plain int64 can fail. Use a nullable integer dtype when missing values must survive.
This preserves missing values instead of forcing you to fill them with a possibly misleading number.
Avoid Row-Wise apply
Timedelta conversion should almost always be vectorized. Using apply row by row is slower and less idiomatic.
Prefer this:
Not this:
Pandas already exposes the efficient vectorized path.
Negative Durations and Business Rules
Durations can be negative. That may be valid, for example when measuring drift, clock skew, or schedule variance. In other domains, negative durations indicate bad data and should be rejected or clamped.
The conversion step itself will happily preserve negative values:
So the real question is not "can pandas convert this" but "what do negative durations mean in my data model."
Name the Output Column by Unit
This sounds minor, but ambiguous column names cause real downstream mistakes. duration_int is worse than duration_seconds. Once the data leaves the notebook or ETL job, explicit unit naming is often the only thing preventing misinterpretation.
That is also why it is better to store one canonical unit and derive display-friendly units later than to scatter mixed-unit columns throughout a pipeline.
Common Pitfalls
The most common mistake is converting timedeltas to integers without defining the target unit. An integer with no unit is almost useless.
Another issue is losing missing values by forcing a non-nullable integer dtype. Use pandas nullable integer types if NaT needs to survive.
Developers also often mix rounding and truncation inconsistently across pipelines. That creates silent disagreements between reports.
Finally, avoid row-wise conversion when vectorized .dt accessors already solve the problem faster and more clearly.
Summary
- Convert pandas timedeltas to integers by first choosing an explicit unit.
- '
.dt.total_seconds()is the standard starting point for seconds-based conversion.' - Scale from seconds or divide by
pd.Timedelta(...)for other units. - Use nullable integer dtypes when missing durations must be preserved.
- Name output columns by unit so downstream code cannot misread them.
Related reading
- python dataframe pandas drop column using int
- Python float argument must be a string or a number, not ''pandas._libs.interval.Interval''
- Python Graph Library
- Python Implementation of OPTICS Clustering Algorithm
- Python Create unix timestamp five minutes in the future
- Python creating a dictionary of lists
- Python implementation of the Wilson `Score` Interval?
- Python in R - Error could not find a Python environment for /usr/bin/python
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.