coding_monkey
coding_monkey

Reputation: 399

Convert formatted string to datetime

I have a dataframe with a column that has been formatted as "%w-%U-%Y" (Weekday number-Week number-Year)

I'm currently doing the following to convert it to datetime format:

for i in df.index:
    df['DWY'][i] = dt.strptime(df['DWY'][i],'%w-%U-%Y')

Is there a more efficient way of doing this?

Upvotes: 2

Views: 49

Answers (2)

Arne
Arne

Reputation: 20117

You could use the map function:

df['DWY'] = list(map(lambda x: dt.strptime(x,'%w-%U-%Y'), df['DWY']))

I personally like the way list comprehension work better:

df['DWY'] = [dt.strptime(entry, '%w-%U-%Y') for entry in df['DWY']]

Upvotes: 1

jezrael
jezrael

Reputation: 862481

Use to_datetime:

df['DWY'] = pd.to_datetime(df['DWY'],format='%w-%U-%Y')

Upvotes: 3

Related Questions