I have an object of type datetime.time
. How do I convert this to an int representing its duration in seconds? Or to a string, which I can then convert to a second representation by splitting?

- 13,519
- 24
- 74
- 118
-
1Duration assumes you have two datetime.time objects and a difference of seconds between them. Are you trying to calculate the difference in seconds between two datetime.time objects? – BoboDarph Jun 29 '17 at 10:55
5 Answers
You can calculate it by yourself:
from datetime import datetime
t = datetime.now().time()
seconds = (t.hour * 60 + t.minute) * 60 + t.second

- 1,746
- 13
- 19
-
Simple and to the point. Very good answer! If you want to include microseconds you can also add "+ (t.microsecond/1000000)" – dsanchez Dec 30 '22 at 20:49
-
OP asks about `datetime.time` object not `datetime.datetime`. Those are different and not fully compatible. Your answer does not work in this case (at least in python3.11). – Mikaelblomkvistsson Aug 18 '23 at 06:26
You need to convert your datetime.time
object into a datetime.timedelta
to be able to use total_seconds()
function.
It will return a float
rather than an int as asked in the question but you can easily cast it.
>>> from datetime import datetime, date, time, timedelta
>>> timeobj = time(12, 45)
>>> t = datetime.combine(date.min, timeobj) - datetime.min
>>> isinstance(t, timedelta)
# True
>>> t.total_seconds()
45900.0
Links I've be inspired by:

- 5,097
- 3
- 27
- 43
As @Owl Max proposed the easiest way to have an integer representation of a time is to use a timedelta. Although, I would like to share a different way to construct the timedelta.
A useful one-liner I like to use is:
import datetime
t = datetime.time(10, 0, 5)
int(datetime.timedelta(hours=t.hour, minutes=t.minute, seconds=t.second).total_seconds())
(ps. Normally this would be a comment)

- 76
- 1
- 4
If your object is supposed to represent a duration, you should use a datetime.timedelta
instead of a datetime.time
.
datetime.time objects are meant to represent a time of the day.
datetime.timedelta objects are meant to represent a duration, and have a total_seconds()
method that does exactly what you want.

- 23,663
- 10
- 44
- 50
Not 100% the answer, but might be relevant in a lot of use-cases:
Suppose you have a pd.Series of such datetime.time
objects (in the example below, the "start" column of the df
pd.DataFrame)
And you want to convert them at once, you can use the pd.TimeDeltaIndex
after the astype("str")
casting.
import pandas as pd
pd.TimedeltaIndex(df['start'].astype("str")).total_seconds()

- 151
- 3
- 8