Alireza Ghaffari
Alireza Ghaffari

Reputation: 1104

How Can python create tuple of tuple with time elements?

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?

Upvotes: 1

Views: 1612

Answers (3)

Andy
Andy

Reputation: 50560

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)

Upvotes: 1

Reut Sharabani
Reut Sharabani

Reputation: 31339

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'))
>>>

Upvotes: 5

user1941407
user1941407

Reputation: 2842

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

Upvotes: 0

Related Questions