Home > OS >  Datetime transformation for column in data frame Python
Datetime transformation for column in data frame Python

Time:12-17

I wanted to transform different date formats to one another. However, when using the print command I still get the old data format. What is it that I'm doing wrong here?

for row in df['created_at']:
    row = datetime.strptime(row, "%Y-%m-%d %H:%M:%S").strftime('%d-%m-%Y')

print(df['created_at'])

CodePudding user response:

In your code, the for loop goes through each element, but it does not save the result. If you try the following code, you will see that your code actually works fine, the result is just "thrown away" after the operation.

for row in df['created_at']:
    row = datetime.strptime(row, "%Y-%m-%d %H:%M:%S").strftime('%d-%m-%Y')
    print(row)

What you want to do is this:

l = []
for row in df['created_at']:
    l.append(datetime.strptime(row, "%Y-%m-%d %H:%M:%S").strftime('%d-%m-%Y'))
print(l)

A more elegant solution is to use list comprehension:

df['created_at'] = [datetime.strptime(row, "%Y-%m-%d %H:%M:%S").strftime('%d-%m-%Y') for row in df['created_at']]
print(df['created_at'])
  • Related