2

Lets say that i have a duration of time e.g., 10 minutes . I have the start time and end time defined .

e.g., start time is 10 A.M and end time is 2 P.M .

I need the time intervals of

10-10.10 , 10.10 - 10.20 , .. , 10.50-11 etc., 

stored in the database .

Here is what i have in mind.

from datetime import datetime
time1 = '10:00'
time2 = '10.10' 
format = '%H:%M'
obj1 = datetime.strptime(time1, format) - datetime.strptime(time2, format)

This is okay for two known intervals . What bout two unknown intervals and to store them in the database?

How can i solve this? Thanks.

Wooble
  • 87,717
  • 12
  • 108
  • 131
Pavan
  • 658
  • 2
  • 7
  • 28

1 Answers1

2

Just store duration, start and end times in the database. You can always generate time intervals later:

def time_range(start, end, duration):
    dt = start
    while dt < end: #note: `end` is not included in the range
        yield dt
        dt += duration

Example

from datetime import datetime, timedelta

# dummy data
duration = timedelta(minutes=10)
start = datetime.utcnow()
end = start + timedelta(hours=16)

# use list instead of tee(), islice() for simplicity 
lst = [dt.strftime('%H:%M') for dt in time_range(start, end, duration)] 
for interval in zip(lst, lst[1:]):
    print "%s-%s," % interval,
print
jfs
  • 399,953
  • 195
  • 994
  • 1,670