William
William

Reputation: 4034

How to append minutes of a day into a list in Python?

I know how to append an item in to a list:

minutes = []

minutes.append('08:30')

my question is,how to loop all the minutes during 8:30am to 15:00,and append them in a list?

format like minutes = ['08:30','08:31',...,15:30] 

or maybe every 10 minutes like

minutes = ['08:30','08:40',...,'15:30']

Any friend can help?

Upvotes: 1

Views: 323

Answers (2)

Nick
Nick

Reputation: 147216

This code will give you an array of string representations of each of the minutes from 08:30 to 15:00:

from datetime import datetime, timedelta

start = datetime.strptime('08:30', '%H:%M')
end = datetime.strptime('15:00', '%H:%M')
delta = timedelta(minutes = 1)
times = []
while start <= end:
    times.append(start.strftime('%H:%M'))
    start += delta
print(times)

Output:

['08:30', '08:31', '08:32', '08:33', ... , '14:57', '14:58', '14:59', '15:00']

You can get times every 10 minutes by changing the minutes value in delta = timedelta(minutes = 1) to 10.

Upvotes: 1

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

You can use pd.date_range:

import pandas as pd
time_list = []
for time in pd.date_range('8:30','15:00', freq='1min').time:
    time_list.append(time.strftime('%H:%M'))
print(time_list)

Output:

['08:30', '08:31', '08:32', '08:33', ... , '14:57', '14:58', '14:59', '15:00']

More succinctly:

>>> pd.date_range('8:30','15:00', freq='1min'
                 ).format(formatter=lambda x:x.strftime('%H:%M'))

['08:30', '08:31', '08:32', '08:33', ... , '14:57', '14:58', '14:59', '15:00']

Upvotes: 2

Related Questions