5

I have a dataframe that has a date column and an hour column.

     DATE         HOUR
  2015-1-1         1
  2015-1-1         2
      .            .
      .            .
      .            .
  2015-1-1         24

I want to convert these columns into a datetime format something like: 2015-12-26 01:00:00

sandrosil
  • 543
  • 3
  • 9
  • 21
  • I am not sure if this is useful since you are using a data frame, If reading off a csv, you can use: datetime.datetime.strptime("2015-1-1 01", "%Y-%m-%d %H") where you can combine the date and hour as string – okkhoy Apr 05 '16 at 03:53
  • @okkhoy I'll give this a try as well. The underlying source is from a csv so maybe before creating the final dataframe I can format the csv. Thanks! – sandrosil Apr 05 '16 at 05:40

1 Answers1

16

You could first convert df.DATE to datetime column and add df.HOUR delta via timedelta64[h]

In [10]: df
Out[10]:
       DATE  HOUR
0  2015-1-1     1
1  2015-1-1     2
2  2015-1-1    24

In [11]: pd.to_datetime(df.DATE) + df.HOUR.astype('timedelta64[h]')
Out[11]:
0   2015-01-01 01:00:00
1   2015-01-01 02:00:00
2   2015-01-02 00:00:00
dtype: datetime64[ns]

Or, use pd.to_timedelta

In [12]: pd.to_datetime(df.DATE) + pd.to_timedelta(df.HOUR, unit='h')
Out[12]:
0   2015-01-01 01:00:00
1   2015-01-01 02:00:00
2   2015-01-02 00:00:00
dtype: datetime64[ns]
Zero
  • 74,117
  • 18
  • 147
  • 154