Home > Net >  python - how do I convert sequence in the dates
python - how do I convert sequence in the dates

Time:05-10

below is my dataframe with one column i.e. Date

df = pd.DataFrame({'Date' : ['2014-03-27', '2014-03-28', '2014-03-31', '2014-04-01', '2014-04-02', '2014-04-03', '2014-04-04', '2014-04-07','2014-04-08', '2014-04-09']})

assume that the dtype is datetime64[ns]

I want to convert it to format %d-%m-%Y

I used this formula

df['Date'].apply(lambda x: datetime.strptime(x.strftime("%d-%m-%Y"),"%d-%m-%Y"))

but the sequencing still didnt change - am I doing something wrong?

CodePudding user response:

df['Date'].apply(lambda x: datetime.strptime(x.strftime("%Y-%m-%d"),"%d-%m-%Y"))

Read it in the way it is, then print it the way you want it.

CodePudding user response:

Use dt.strftime:

df["Date"] = df["Date"].dt.strftime("%d-%m-%Y")

CodePudding user response:

You example dataset doesn't have data of type datetime64[ns], so lets convert them first

Code

import pandas as pd
import datetime

# your dataset
df = pd.DataFrame({'Date': ['2014-03-27', '2014-03-28', '2014-03-31', '2014-04-01', '2014-04-02', '2014-04-03', '2014-04-04', '2014-04-07','2014-04-08', '2014-04-09']})

# convert to datetime64[ns] type
df['Date']=df['Date'].apply(lambda x: datetime.datetime.strptime(x, "%Y-%m-%d"))
print(df['Date'].dtype)

# convert to formatted string
df['Date']=df['Date'].apply(lambda x: x.strftime("%d-%m-%Y"))
print(df)

Output

datetime64[ns]

         Date
0  27-03-2014
1  28-03-2014
2  31-03-2014
3  01-04-2014
4  02-04-2014
5  03-04-2014
6  04-04-2014
7  07-04-2014
8  08-04-2014
9  09-04-2014
  • Related