Pandas: How to set hour of a datetime from another column?

Viewed 990

I have a dataframe including a datetime column for date and a column for hour.

like this:

min hour    date    
0   0   2020-12-01  
1   5   2020-12-02  
2   6   2020-12-01

I need a datetime column including both date and hour.

like this :

min hour    date        datetime
0   0   2020-12-01  2020-12-01 00:00:00
0   5   2020-12-02  2020-12-02 05:00:00 
0   6   2020-12-01  2020-12-01 06:00:00

How can I do it?

3 Answers

Use pd.to_datetime and pd.to_timedelta:

In [393]: df['date'] = pd.to_datetime(df['date'])

In [396]: df['datetime'] = df['date'] +  pd.to_timedelta(df['hour'], unit='h')
    
In [405]: df
Out[405]: 
   min  hour       date            datetime
0    0     0 2020-12-01 2020-12-01 00:00:00
1    1     5 2020-12-02 2020-12-02 05:00:00
2    2     6 2020-12-01 2020-12-01 06:00:00

You could also try using apply and np.timedelta64:

df['datetime'] = df['date'] + df['hour'].apply(lambda x: np.timedelta64(x, 'h'))
print(df)

Output:

   min  hour       date            datetime
0    0     0 2020-12-01 2020-12-01 00:00:00
1    1     5 2020-12-02 2020-12-02 05:00:00
2    2     6 2020-12-01 2020-12-01 06:00:00

In the first question it is not clear the data type of columns, so i thought they are in date (not pandas) and he want the datetime version.

If this is the case so, solution is similar to the previous, but using a different constructor.

from datetime import datetime
df['datetime'] = df.apply(lambda x: datetime(x.date.year, x.date.month, x.date.day, int(x['hour']), int(x['min'])), axis=1)
Related