Search code examples
pythonfor-looptuplespython-datetime

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?


Solution

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