Convert Column to Date Format (Pandas Dataframe)

How to change the datetime format in Pandas

You can use dt.strftime if you need to convert datetime to other formats (but note that then dtype of column will be object (string)):

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

Convert DataFrame column type from string to datetime

The easiest way is to use to_datetime:

df['col'] = pd.to_datetime(df['col'])

It also offers a dayfirst argument for European times (but beware this isn't strict).

Here it is in action:

In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0 2005-05-23 00:00:00
dtype: datetime64[ns]

You can pass a specific format:

In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0 2005-05-23
dtype: datetime64[ns]

Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

Use '%Y-%m-%d'

Ex:

import pandas as pd

df = pd.DataFrame({"Date": ["26-12-2007", "27-12-2007", "28-12-2007"]})
df["Date"] = pd.to_datetime(df["Date"]).dt.strftime('%Y-%m-%d')
print(df)

Output:

         Date
0 2007-12-26
1 2007-12-27
2 2007-12-28

Convert Pandas Column to DateTime

Use the to_datetime function, specifying a format to match your data.

raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

Pandas - Converting date column from dd/mm/yy hh:mm:ss to yyyy-mm-dd hh:mm:ss

If you know you will have a consistent format in your column, you can pass this to to_datetime:

df['sale_date'] = pd.to_datetime(df['sale_date'], format='%d/%m/%y %H:%M:%S')

If your formats aren't necessarily consistent but do have day before month in each case, it may be enough to use dayfirst=True though this is difficult to say without seeing the data:

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

Convert the column type from string to datetime format in Pandas dataframe

The above error was resolved with the below code, as there was some mismatch in the format of the date.

DOB_Permits["job_start_date"] = pd.to_datetime(DOB_Permits["job_start_date"], errors='coerce', format="%y%m%d")

Convert column to date when date in format dd.mm.yyyy

You can use pandas to_datetime:

import pandas as pd
d = {"Date": ["23.11.2020", "22.10.1990", "31.12.1890"], "Col1": ["V1", "V2", "V4"], "Col2": [100, 200, 79]}
df = pd.DataFrame(d)
df["Date"] = pd.to_datetime(df["Date"], format='%d.%m.%Y', errors='coerce').dt.date
df

Date Col1 Col2
0 2020-11-23 V1 100
1 1990-10-22 V2 200
2 1890-12-31 V4 79

df.dtypes

Date object
Col1 object
Col2 int64
dtype: object


Related Topics



Leave a reply



Submit