When fetching rows from my database containing time ex 15:15:15 h/m/s. I get those in timedelta objects, i want them in time object so I later can combine them with a date object and get a datetime object.
for row in results:
startDate = row['startDate']
StartTime = row['startTime']
myListStartDate.append(datestart)
myListTimeStart.append(startTime)
When i put all the startTimes in a list and prints the list i get datetime.timedelta(0, 54900). So how do convert the timedelta to a time object so I later can compare it to other time objects.
A timedelta has only one method called timedelta. total_seconds() . This method returns the total number of seconds the duration has. If we want to convert a timedelta object to seconds, we can just call it.
Call timedelta. seconds to return the number of seconds. Use this result and the integer division symbol // to divide the seconds by 3600 to calculate the number of hours.
To get the Total seconds in the duration from the Timedelta object, use the timedelta. total_seconds() method.
Here's how I would do it.
>>> import datetime
>>> startTime = datetime.timedelta(0, 54915)
>>> startTime = (datetime.datetime.min + startTime).time()
>>> startTime
datetime.time(15, 15, 15)
Credit goes to this post.
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