0

I was working on code to generate the time for an entire day with 30 second intervals. I tried using DT.datetime and DT.time but I always end up with either a datetime value or a timedelta value like (0,2970). Can someone please tell me how to do this.

So I need a list that has data like:

[00:00:00] [00:00:01] [00:00:02]

till [23:59:59] and needed to compare it against a datetime value like 6/23/2011 6:38:00 AM.

Thanks!

gran_profaci
  • 8,087
  • 15
  • 66
  • 99
  • Can't you just extract the seconds from the datatime value and see if they're equal to the boundary of a 30 second interval (0 or 30)? This would be much quicker than doing any kind of search through a list of values and you wouldn't need to create the list. – martineau Apr 09 '13 at 08:29

2 Answers2

0

There's a great answer on how to get a list of incremental values for seconds for a 24-hour day. I reused a part of it.

  • Note 1. I'm not sure how you're thinking of comparing time with datetime. Assuming that you're just going to compare the time part and extracting that.
  • Note 2. The time.strptime call expects a 12-hour AM/PM-based time, as in your example. Its result is then passed to time.strftime that returns a 24-hour-based time.

Here's what I think you're looking for:

my_time = '6/23/2011 6:38:00 AM' # time you defined

from datetime import datetime, timedelta
from time import strftime, strptime

now = datetime(2013, 1, 1, 0, 0, 0)
last = datetime(2013, 1, 1, 23, 59, 59)
delta = timedelta(seconds=1)

times = []
while now <= last:
    times.append(now.strftime('%H:%M:%S'))
    now += delta

twenty_four_hour_based_time = strftime('%H:%M:%S', strptime(my_time, '%m/%d/%Y %I:%M:%S %p'))
twenty_four_hour_based_time in times # returns True
Community
  • 1
  • 1
Alex Yarmula
  • 10,477
  • 5
  • 33
  • 32
0

Is there a reason you want to use datetimes instead of just 3 for loops counting up? Similarly, do you want to do something fancy or do you want to just compare against the time? If you don't need to account for leap seconds or anything like that, just do it the easy way.

import datetime

now = datetime.datetime.now()

for h in xrange(24):
    for m in xrange(60):
        for s in xrange(60):
           time_string = '%02d:%02d:%02d' % (h,m,s)
           if time_string == now.strftime('%H:%m:%S'):
               print 'you found it! %s' % time_string

Can you give any more info about why you are doing this? It seems like you would be much much better off parsing the datetimes or using strftime to get what you need instead of looping through 60*60*24 times.

Collin Green
  • 2,146
  • 14
  • 12