0

This question is related to the thread How to change the datetime format in pandas

The solutions presented there work fine for one date, but what if you have different dates in the same dataframe?

For instance, my dates in datetime are

2016-01-26
2016-01-27
2016-01-28
2016-01-29

Code as in the other thread where the same date is used twice:

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016', 1: '26/1/2016'}})
print (df)
         DOB
0  26/1/2016 
1  26/1/2016

df['DOB'] = pd.to_datetime(df.DOB)
print (df)
         DOB
0 2016-01-26
1 2016-01-26

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print (df)
         DOB        DOB1
0 2016-01-26  01/26/2016
1 2016-01-26  01/26/2016

I also found this code on (I think it was) datetime to string with series in python pandas

df['DOB1'] = df['DOB'].apply(lambda x:x.strftime('%m/%d/%Y'))

And this one:

df['DOB1'] = df['DOB'].map(lambda x:x.strftime('%m/%d/%Y'))

For instance in my dataframe DOB I have the following dates and would like to have them in a different format.

My dates in Datetime format:

0  2016-01-26
1  2016-01-27
2  2016-01-28  
3  2016-01-29  

Desired output:

01/26/2016
01/27/2016
01/28/2016
01/29/2016

I've been using the same codes as above but when I run them (no matter which of the codes) ALL the dates get turned into

01/26/2016
01/26/2016
01/26/2016
01/26/2016

It seems like pandas takes the first value and applies it to the rest of the dataframe. How can I make pandas read and convert each of the dates differently?

Thank you!

Py_Bear
  • 23
  • 5
  • can we see the exact code you used to convert your 2nd code block to your 3rd code block – zero May 10 '19 at 09:02

2 Answers2

0

I run your code, and the results are as you expected.

import pandas as pd
df = pd.DataFrame({'DOB': {0: '26/1/2016', 1: '27/1/2016', 2: '28/1/2016'}})
df['DOB'] = pd.to_datetime(df.DOB)
df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')

Result:

         DOB        DOB1
0 2016-01-26  01/26/2016
1 2016-01-27  01/27/2016
2 2016-01-28  01/28/2016

Without knowing more details, I would suggest you create a function and apply it to your column.

convert_date = lambda i: i.strftime('%m/%d/%Y')
df['DOB'].apply(convert_date)

0    01/26/2016
1    01/27/2016
2    01/28/2016
N. Arunoprayoch
  • 922
  • 12
  • 20
0

Thank you for looking into this. I caught my mistake and it's kind of embarrasing but I do want to leave the question in here - also to show other beginners where you can go wrong without catching the mistake at first. I also owe the kind persons who provided a reply an explanation.

It's true that I actually did use the above code as an example. BUT in my code I forgot to include %d in strftime. So, of course dates like

2016-01-26
2016-01-27
2016-01-28
2016-01-29

would be converted to

2016\01
2016\01
2016\01
2016\01

However, only when N. Arunoprayoch replied did I see it!!! I wonder how I could I miss that??

Sorry about that and thanks again for your help!

Py_Bear
  • 23
  • 5