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

2
  • 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 Commented Apr 5, 2016 at 3: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! Commented Apr 5, 2016 at 5:40

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.