1

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.

Dimpermanence
  • 47
  • 1
  • 9

3 Answers3

1

How about this:

rec2.hour*3600 + rec2.minute*60 + rec2.second

I also found this:

Get seconds since midnight in python

Community
  • 1
  • 1
davejagoda
  • 2,420
  • 1
  • 20
  • 27
  • Obviously this is a good question because I felt it was pretty straightforward : ) I simply want to convert the time portion of datetime to seconds. And these seconds need to be of type integer, not string. – Dimpermanence Nov 17 '15 at 22:25
  • Argghh...see, that's what I'm doing but it looks...well, convoluted. Not yours, mine. Because mine has more steps and after a while it's like "c'mon, really?" – Dimpermanence Nov 17 '15 at 22:31
  • It does seem like there should be a simple way given a date to get seconds since midnight, but I haven't found anything better than this yet. – davejagoda Nov 17 '15 at 22:34
  • Well, I'm currently using this: s = int(sum(int(i) * 60**index for index, i in enumerate(rec2.split(":")[::-1]))) and this works but it's ridiculously complicated. – Dimpermanence Nov 17 '15 at 22:35
  • Actually, that seems like a clever answer, please post it. – davejagoda Nov 17 '15 at 22:36
  • It's one a grabbed from a similar post. I will do so and cite the other developer and will just roll the dice on whether this will be marked as duplicate. – Dimpermanence Nov 17 '15 at 22:38
1

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.

Community
  • 1
  • 1
Dimpermanence
  • 47
  • 1
  • 9
0

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
Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670