0

Suppose I have following data with data formats:

date time
2022-04-21 610
2022-04-22 610
2022-04-22 1751

date: object

time: int32

I wish to combine date column and time column to make new column 'datetime' with datetime format like this:

date time datetime
2022-04-21 610 2022-04-21 6:10
2022-04-22 610 2022-04-22 7:01
2022-04-22 1751 2022-04-22 17:51

When I use following codes, I get errors as following:

  1. Converting object to datetime

    df['date'] = pd.to_datetime(df['date'], format='%Y-%M-%d')

date time
2022-01-21 00:04:00 610
2022-01-22 00:04:00 610
2022-01-22 00:04:00 1751
  1. Converting int32 to datetime

    df_trade['time'] = pd.to_datetime(df_trade['time'], format='%H:%M')

ValueError: time data '610' does not match format '%H:%M' (match)

I guess the last step must be easy with following code, but columns are not in the right format to combine.

df_trade['datetime'] = df_trade['date'].astype(str)+" "+df_trade['time'].astype(str)

How do I convert the object, int32 columns into datetime format without changing the contents?

1 Answer 1

2

You are close, all your solution should be combined, only change few typos - for months need %m and for parse times need remove : - %H%M:

df_trade['datetime'] = pd.to_datetime(df_trade['date'] +' '+ df_trade['time'].astype(str), 
                                      format='%Y-%m-%d %H%M')
print (df_trade)
         date  time            datetime
0  2022-04-21   610 2022-04-21 06:10:00
1  2022-04-22   610 2022-04-22 06:10:00
2  2022-04-22  1751 2022-04-22 17:51:00
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.