1

I wanna create a tuple like this:

(('0', '00:00:00'), ('1', '00:30:00'), ('2', '00:01:00') ..., ('46', '23:00:00'), ('47', '23:30:00'))

Attempts:

lines = []
a = datetime.timedelta(minutes=0)
for ii in range (48):
    lines.append(a)
    a = a.timedelta(minutes=30)

I tried various ways, but I don't know really what should I do?

1
  • 1
    Post your attempts.. Commented Aug 16, 2015 at 6:35

3 Answers 3

5

This feels like something that can be done with datetime and timedelta objects.

For the tuple creation tuple I've used a generator expression.

>>> from datetime import datetime, timedelta
>>> dt = datetime(1970 ,1 ,1)
>>> t = timedelta(minutes=30)
>>> tuple((str(i), (dt + (i * t)).strftime("%X")) for i in range(48))
(('0', '00:00:00'), ..., ('47', '23:30:00'))
>>>
Sign up to request clarification or add additional context in comments.

Comments

1

You can utilize a generator to build a list of times at 30 minute intervals.

def yield_times():  
    start = datetime.combine(date.today(), time(0, 0))
    yield start.strftime("%H:%M:%S")
    while True:
        start += timedelta(minutes=30)
        yield start.strftime("%H:%M:%S")

Using this generator, we can create a list of tuples. 48 in this case, is the number of iterations through the generator. This range statement will start at 0, giving us values 0 - 47.

gen = yield_times()
tuple_list = []
for ii in range(48):
    tuple_list.append((ii, gen.next()))

Finally, we need to convert the list of tuples to a tuple of tuples:

tuple_times = tuple(tuple_list)

Full script:

from datetime import date, time, datetime, timedelta
def yield_times():  
    start = datetime.combine(date.today(), time(0, 0))
    yield start.strftime("%H:%M:%S")
    while True:
        start += timedelta(minutes=30)
        yield start.strftime("%H:%M:%S")

gen = yield_times()
tuple_list = []
for ii in range(48):
    tuple_list.append((ii, gen.next()))

tuple_times = tuple(tuple_list)

1 Comment

Thanks, but Traceback (most recent call last): File "<input>", line 12, in <module> AttributeError: 'generator' object has no attribute 'next'
0

Try use list with tuple convertion

l = []
for i in xrange(10):
    l.append(('1', '00:30:00'))   <--- set your data here
t  =tuple(l)   # convert it to tuple

2 Comments

thanks, but how can I add to the time 30 minutes each time?
use datetime.timedelta function for creating and strptime to string convertion

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.