Odisseo
Odisseo

Reputation: 777

Create Datetime Column from Integer Column - Hours and Minutes

I have a dataframe with a 4 digit int column:

df['time'].head(10)
0    1844
1    2151
2    1341
3    2252
4    2252
5    1216
6    2334
7    2247
8    2237
9    1651
Name: DepTime, dtype: int64

I have verified that max is 2400 and min is 1. I would like to convert this to a date time column with hours and minutes. How would I do that?

Upvotes: 0

Views: 537

Answers (4)

Andy L.
Andy L.

Reputation: 25269

If you want output in string format of HH:MM, you just need to convert column to string and use str.slice_replace with : (Note: I change your sample to include case of 3-digit integer)

sample df:

     time
0    1844
1    2151
2    1341
3    2252
4    2252
5    216
6    2334
7    2247
8    2237
9    1651

s = df['time'].map('{0:04}'.format)
out = s.str.slice_replace(2,2,':')

Out[666]:
0    18:44
1    21:51
2    13:41
3    22:52
4    22:52
5    02:16
6    23:34
7    22:47
8    22:37
9    16:51
Name: time, dtype: object

Or split and concat with :

s = df['time'].map('{0:04}'.format)
out = s.str[:2] + ':' + s.str[2:]

Out[665]:
0    18:44
1    21:51
2    13:41
3    22:52
4    22:52
5    02:16
6    23:34
7    22:47
8    22:37
9    16:51
Name: time, dtype: object

Upvotes: 0

BENY
BENY

Reputation: 323376

IIUC

pd.to_datetime(df.time.astype(str),format='%H%M').dt.strftime('%H:%M')
Out[324]: 
0    21:51
1    13:41
2    22:52
3    22:52
4    12:16
5    23:34
6    22:47
7    22:37
8    16:51
Name: col2, dtype: object

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150805

If these are 4 digits, timedelta is more appropriate than datetime:

pd.to_timedelta(df['time']//100 * 60 + df['time'] % 100, unit='m')

Output:

0   18:44:00
1   21:51:00
2   13:41:00
3   22:52:00
4   22:52:00
5   12:16:00
6   23:34:00
7   22:47:00
8   22:37:00
9   16:51:00
Name: time, dtype: timedelta64[ns]

If you have another column date, you may want to merge date and time to create a datetime column.

Upvotes: 2

DarkDrassher34
DarkDrassher34

Reputation: 59

Try this!

df['conversion'] = (df['time'].apply(lambda x: pd.to_datetime(x, format = '%H%M')).dt.strftime('%H:%M'))

Upvotes: 0

Related Questions