18

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?

Bluefire
  • 12,429
  • 22
  • 67
  • 111
  • 1
    Duration 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

4 Answers4

30

You can calculate it by yourself:

from datetime import datetime

t = datetime.now().time()
seconds = (t.hour * 60 + t.minute) * 60 + t.second
bakatrouble
  • 1,652
  • 10
  • 18
20

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:

Kruupös
  • 4,484
  • 3
  • 24
  • 39
5

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.

Thierry Lathuille
  • 22,718
  • 10
  • 38
  • 45
4

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)

Kostas
  • 56
  • 4