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?
To convert a datetime to seconds, subtracts the input datetime from the epoch time. For Python, the epoch time starts at 00:00:00 UTC on 1 January 1970. Subtraction gives you the timedelta object. Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch.
To convert hh:mm:ss to seconds:Convert the hours to seconds, by multiplying by 60 twice. Convert the minutes to seconds by multiplying by 60 .
To convert time to minutes, multiply the time by 1440, which is the number of minutes in a day (24*60). To convert time to seconds, multiply the time time by 86400, which is the number of seconds in a day (24*60*60 ).
You can calculate it by yourself:
from datetime import datetime
t = datetime.now().time()
seconds = (t.hour * 60 + t.minute) * 60 + t.second
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:
datetime.time
to datetime.timedelta
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With