Spooked
Spooked

Reputation: 596

Setting the date time format to multiple columns of a dataframe at once Python

I have two columns in my DataFrame which I format to a specific time format. It works with two lines of code below but I want to combine into one command

df['Time01'] = pd.to_datetime(Time_01).strftime('%H:%M:%S')
df['Time02'] = pd.to_datetime(Time_02).strftime('%H:%M:%S')

I have tried the following

df[['Time_01','Time_02']].apply(pd.to_datetime, format = '%H:%M:%S')

But get the following error message

None of [Index(['Time_01', 'Time_02'], dtype='object')] are in the [columns]

New python and pandas any help appreciated

Upvotes: 0

Views: 178

Answers (1)

user7864386
user7864386

Reputation:

You proposed solution doesn't work because as the error says, there are no columns "Time_01" and "Time_02" yet in df and Time_01 and Time_02 that are converted to pandas datetime objects are objects independent of df. One way to write the first two lines into a single line is to write it in a dict comprehension and pass the resulting dictionary to the assign method:

df = df.assign(**{f'Time0{i+1}': pd.to_datetime(lst).strftime('%H:%M:%S') 
                  for i, lst in enumerate((Time_01, Time_02))})

Upvotes: 1

Related Questions