1

i'm relatively new to Python

I have a column of data which represents time of the day - but in an integer format hhmm - i.e. 1230, 1559.

I understand that this should be converted to a correct time format so that it can be used correctly.

I've spent a while googling for an answer but I haven't found a definitive solution.

Thank you

Ben G
  • 95
  • 9

1 Answers1

2

If need datetimes, also are necessary dates by function to_datetime, for times add dt.time.

Another solution is convert values to timedeltas - but is necessary format HH:MM:SS:

df = pd.DataFrame({'col':[1230,1559]})

df['date'] = pd.to_datetime(df['col'], format='%H%M')
df['time'] = pd.to_datetime(df['col'], format='%H%M').dt.time

s = df['col'].astype(str)
df['td'] = pd.to_timedelta(s.str[:2] + ':' + s.str[2:] + ':00')
print (df)
    col                date      time       td
0  1230 1900-01-01 12:30:00  12:30:00 12:30:00
1  1559 1900-01-01 15:59:00  15:59:00 15:59:00

print (df.dtypes)
col               int64
date     datetime64[ns]
time             object
td      timedelta64[ns]
dtype: object
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • So the column would have to have a 'dummy' date as well as the time? – Ben G Feb 27 '19 at 10:22
  • @BenG - exactly, if need datetimes, not exist only times with no dates – jezrael Feb 27 '19 at 10:23
  • @BenG you can drop the 'dummy' date column after extracting the time – BHC Feb 27 '19 at 10:26
  • I'm not sure if I can ask another question here - but is there a simple way to filter this (time) column based on values? – Ben G Feb 27 '19 at 11:26
  • @BenG - Do you think something like [this](https://stackoverflow.com/q/17071871) ? – jezrael Feb 27 '19 at 11:27
  • I understand how basic filtering works with pandas (.loc/.iloc etc). However this format type is new to me. I just want to create a new column that has the values 'morning', 'afternoon' and 'evening' dependent on the values in the time column. – Ben G Feb 27 '19 at 11:31
  • But my data is in datetime.time format and not datetime? – Ben G Feb 27 '19 at 11:36
  • @BenG - So use `df['date'] = pd.to_datetime(df['col'], format='%H%M').dt.hour` - need datetimes – jezrael Feb 27 '19 at 11:37