Reputation: 55
I have a script that returns a datetime object like so:
rec = record[14] #index 14 is a straight datetime object
rec2 = rec.time() #sends time part to rec2
All I want to do now is convert rec2 to seconds of type integer. Any insight on how to do this would be greatly appreciated.
Upvotes: 1
Views: 463
Reputation: 414149
The question "Python Time conversion h:m:s to seconds" (that you've linked) shows a simple efficient one-line solution on how to get an integer number of seconds since midnight that works for both datetime.datetime
and datetime.time
types:
from datetime import timedelta
secs = timedelta(hours=rec.hour, minutes=rec.minute, seconds=rec.second).seconds
Upvotes: 0
Reputation: 55
I had "solved" this conundrum earlier by adopting code from a similar question, although I had really hoped there was a more direct way. I took @Nolen Royalty's "cheeky" one liner and wrapped it in the int() function is all. In essence:
rec = record[14] #stores index 14 of a list to rec which is a full datetime object
rec2 = rec.time() #stores time portion of that datetime object to rec2
rec3 = rec2.strftime('%H:%M:%S') #uses strftime to convert to string
s = int(sum(int(i) * 60**index for index, i in enumerate(rec3.split(":")[::-1]))) #converts that string to integer
Convoluted, but it works...still, if anyone has anything better I would be very intrigued.
Upvotes: 1
Reputation: 2528
How about this:
rec2.hour*3600 + rec2.minute*60 + rec2.second
I also found this:
Get seconds since midnight in python
Upvotes: 1