Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert datetime.time to seconds

Tags:

python

time

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?

like image 239
Bluefire Avatar asked Jun 29 '17 10:06

Bluefire


People also ask

How do I convert datetime to seconds?

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.

How do you convert HH MM SS to seconds?

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 .

How do I convert datetime to minutes?

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 ).


2 Answers

You can calculate it by yourself:

from datetime import datetime

t = datetime.now().time()
seconds = (t.hour * 60 + t.minute) * 60 + t.second
like image 83
bakatrouble Avatar answered Sep 21 '22 14:09

bakatrouble


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:

  • SO question on datetime.combine
  • SO question about converting datetime.time to datetime.timedelta
like image 39
Kruupös Avatar answered Sep 19 '22 14:09

Kruupös