Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 356
Arya Sadeghi Avatar asked Jan 03 '21 08:01

Arya Sadeghi


People also ask

How do I calculate time difference between two columns in pandas?

To calculate time difference between two Python Pandas columns in hours and minutes, we can subtract the datetime objects directly. We create a Panda DataFrame with 3 columns. Then we set the values of the to and fr columns to Pandas timestamps.

How do I combine two datetime columns in Python?

Combine Date and Time Columns The first column holds date values of type datetime. date and the other holds time values of type datetime. time. We convert the columns to string type and concatenate them using the addition operator in Python.


2 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
like image 105
Mayank Porwal Avatar answered Oct 26 '22 15:10

Mayank Porwal


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
like image 30
U12-Forward Avatar answered Oct 26 '22 15:10

U12-Forward