1

I am struggling to convert an object type to datetime. It's a column from a dataframe that has values in format dd.mm.yyyy (e.g. 13.03.2021).

dataframe: df

column: time

values in format: dd.mm.yyyy

desired output: dd-mm-yyyy

Below are the options which I already tried, but it does not work out.

df['time'] = pd.to_timedelta(df['time'].astype(str))

df['time'] = datetime.strptime(df['time'], '%d-%m-%Y').date()

df['time'] = pd.to_datetime(df['time'], format='%d-%m-%Y')

df['time'] = pd.to_datetime(df['time'], dayfirst=True)

Any ideas? Thank you so much in advance.

2
  • Have you tried, df['time'] = pd.to_datetime(df['time'], infer_datetime_format=True)? Commented Mar 13, 2021 at 17:46
  • pd.to_datetime(df['time'], format='%d.%m.%Y') Commented Mar 13, 2021 at 17:48

3 Answers 3

1

Using datetime and strptime along with strftime would suffice the need. Hope the below code helps.

import pandas as pd
import datetime

data = ['13.03.2021','23.03.2021']
df = pd.DataFrame(data,columns=['time'])

new_date = []
for x in df['time']:
   new_date.append(datetime.datetime.strptime(str(x), '%d.%m.%Y').strftime('%d-%m-%y'))
df = pd.DataFrame(new_date,columns=['time'])
print(df)

Output

Image

Sign up to request clarification or add additional context in comments.

1 Comment

Why do I get error message "time data ' 13.03.2021' does not match format '%d.%m.%Y' (match)"?
1

To get the format you want in the database, you can convert the time string to a datetime object, then format it to the string you want:

>>> import pandas as pd
>>> df=pd.DataFrame(['01.02.2001','02.03.2002'],columns=['time'])
>>> df
         time       # dtype=object
0  01.02.2001
1  02.03.2002
>>> df.time = pd.to_datetime(df.time,format='%d.%m.%Y')
>>> df
        time        # dtype=datetime64
0 2001-02-01
1 2002-03-02
>>> df.time = df.time.dt.strftime('%d-%m-%Y')
>>> df
         time       # dtype=object
0  01-02-2001
1  02-03-2002

Comments

0
import pandas as pd
import datetime
d = {
    "time":['13.03.2021', '12.03.2021','11.03.2021']
}
df = pd.DataFrame(data=d)
df['time'] = pd.to_datetime(df['time'], infer_datetime_format=True)
for i in range(0,len(df)):
  x=(str(df['time'][i])[:10])
  df['time'][i]=datetime.datetime.strptime(x, '%Y-%m-%d').strftime('%d-%m-%y')

Output -

    time
0   13-03-21
1   12-03-21
2   11-03-21   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.