Convert datetime.time to seconds

Viewed 46719

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?

4 Answers

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)

Related