Marlon Teixeira
Marlon Teixeira

Reputation: 393

How to convert a list of hour and minutes strings to datetime without adding year using pandas?

I have dataframe indexed by datetime and I want to make a dictionary with hours and minutes. For that matter I do the following:

lista = list(set(perfis.index.strftime('%H:%M').tolist()))

which returns

['01:00', '17:00', '19:00', '21:00', '19:15', '07:15', '18:30', '05:45', '15:30',..., '04:00', '11:30']

Now I want to order it and for that matter I want to recovert it to datetime:

pd.to_datetime(lista, format='%H:%M')

Which gives me

DatetimeIndex(['1900-01-01 01:00:00', '1900-01-01 17:00:00',
               '1900-01-01 19:00:00', '1900-01-01 21:00:00',
               '1900-01-01 19:15:00', '1900-01-01 07:15:00',
               '1900-01-01 18:30:00', '1900-01-01 05:45:00',
               '1900-01-01 15:30:00', ..., '1900-01-01 11:30:00'],
              dtype='datetime64[ns]', freq=None)

However, I just want the hours and minutes and if I use time I get

[datetime.time(1, 0) datetime.time(17, 0) datetime.time(19, 0)
 datetime.time(21, 0) datetime.time(19, 15) datetime.time(7, 15)
 datetime.time(18, 30) datetime.time(5, 45) datetime.time(15, 30)
 datetime.time(11, 30)]

How can I get a list of ordered datetime entries only with hours and minutes?

Upvotes: 0

Views: 229

Answers (1)

not_speshal
not_speshal

Reputation: 23156

You can just sort the list using sorted:

lista = sorted(list(set(perfis.index.strftime('%H:%M').tolist())))

Upvotes: 2

Related Questions