Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Pandas column for datetime from year / month/ day / hour / minute / second?

Tags:

python

pandas

I am trying to construct a datetime column in Pandas that represents multiple columns describing the year, month, day, etc. Most of the other answers I can find on this topic involve processing data in the opposite direction (from datetime to integer hour, for instance).

df = pd.DataFrame()

df['year'] = [2019, 2019, 2019, 2019, 2019, 2019]
df['month'] = [8, 8, 8, 8, 8, 8]
df['day'] = [1, 1, 1, 1, 1, 1]
df['hour'] = [10,10,11,11,12,12]
df['minute'] = [15,45,20,40,10,50]
df['second'] = [0, 1, 5, 10, 10, 11]

Goal:

df['datetime_val'] = 
0   2019-08-01 10:15:00
1   2019-08-01 10:45:01
2   2019-08-01 11:20:05
3   2019-08-01 11:40:10
4   2019-08-01 12:10:10
5   2019-08-01 12:50:11
Name: datetime_vals, dtype: datetime64[ns]

In the example above, how could I rapidly create a datetime column representing the constituent time information? I could easily do this with .apply() and a helper function but I envision performing this operation for millions of rows. I would love something inbuilt / vectorized. Thanks!

like image 334
MattM Avatar asked Dec 17 '22 16:12

MattM


1 Answers

IIUC to_datetime can take dataframe , only if the columns is well named as yours

pd.to_datetime(df)
0   2019-08-01 10:15:00
1   2019-08-01 10:45:01
2   2019-08-01 11:20:05
3   2019-08-01 11:40:10
4   2019-08-01 12:10:10
5   2019-08-01 12:50:11
dtype: datetime64[ns]
like image 55
BENY Avatar answered Dec 28 '22 10:12

BENY