Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to Convert String to Float in Pandas DataFrame
Next article icon

Change String To Date In Pandas Dataframe

Last Updated : 17 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Working with date and time data in a Pandas DataFrame is common, but sometimes dates are stored as strings and need to be converted into proper date formats for analysis and visualization. In this article, we will explore multiple methods to convert string data to date format in a Pandas DataFrame.

Using pandas.to_datetime()

This is the most commonly used method to convert string dates into datetime64[ns] format. It automatically detects and converts various date formats, making it efficient for handling standard date strings.

Python
import pandas as pd  data = {     'Date': ['2022-01-01', '2022-01-02', '2022-01-03'],     'Values': [100, 200, 300] }  # Creating DataFrame df = pd.DataFrame(data)  # Using pandas.to_datetime() df['Date'] = pd.to_datetime(df['Date']) print(df.dtypes) 

Output
Date      datetime64[ns] Values             int64 dtype: object 

Explanation: This code creates a DataFrame from a dictionary with date strings and numerical values, then converts the 'Date' column to datetime64[ns] using pandas.to_datetime() for proper date handling.

Using datetime.strptime()

This method is useful when dealing with custom date formats. The strptime() function from Python’s datetime module allows precise control over how dates are parsed by specifying a format string.

Python
import pandas as pd from datetime import datetime  data = {     'Date': ['01-01-2022', '02-01-2022', '03-01-2022'],     'Values': [100, 200, 300] }  # Creating DataFrame df = pd.DataFrame(data)  # Custom format conversion df['Date'] = df['Date'].apply(lambda x: datetime.strptime(x, '%d-%m-%Y'))  print("\nAfter converting") print(df.dtypes) 

Output
After converting Date      datetime64[ns] Values             int64 dtype: object 

Explanation: This code creates a DataFrame with date strings in DD-MM-YYYY format and numerical values. It uses apply() with datetime.strptime() to convert each date string into a datetime object for proper date handling.

Using pd.Series.dt.strftime()

Once a column is converted to a datetime64 type, strftime() helps format it into a specific date string format (e.g., DD-MM-YYYY). This method is useful for displaying dates in a customized way.

Python
import pandas as pd  data = {     'Date': ['2022-01-01', '2022-01-02', '2022-01-03'],     'Values': [100, 200, 300] }  # Creating DataFrame df = pd.DataFrame(data)  # Convert Date column to datetime df['Date'] = pd.to_datetime(df['Date'])  # Convert Date column to a different format df['Formatted_Date'] = df['Date'].dt.strftime('%d-%m-%Y')  print(df) 

Output
        Date  Values Formatted_Date 0 2022-01-01     100     01-01-2022 1 2022-01-02     200     02-01-2022 2 2022-01-03     300     03-01-2022 

Explanation:The code converts date strings to datetime using pd.to_datetime() and formats them as DD-MM-YYYY using .dt.strftime(), storing the result in 'Formatted_Date'.

Using astype()

astype() method allows direct conversion of a column’s data type. When applied to a date column, it converts strings to datetime64[ns]. However, it requires that all values follow a uniform date format.

Python
import pandas as pd  data = {     'Date': ['2022-01-01', '2022-01-02', '2022-01-03'],     'Values': [100, 200, 300] }  # Creating DataFrame df = pd.DataFrame(data)  # Using DataFrame.astype() df['Date'] = df['Date'].astype('datetime64[ns]')  print("\nAfter converting") print(df.dtypes) 

Output
After converting Date      datetime64[ns] Values             int64 dtype: object 

Explanation: This code creates a DataFrame with date strings and numerical values, then uses astype('datetime64[ns]') to convert the 'Date' column into a datetime format, enabling efficient date-based operations.

Handling different date formats in column

When a column contains multiple date formats, pandas.to_datetime() can be used with errors='coerce', which replaces invalid date formats with NaT (Not a Time). This ensures the dataset remains clean and properly formatted.

Python
import pandas as pd  data = {     'Date': ['2022-01-01', '01-02-2022', 'March 3, 2022', 'Invalid Date'],     'Values': [100, 200, 300, 400] }  # Creating DataFrame df = pd.DataFrame(data)  # Handling multiple date formats df['Date'] = pd.to_datetime(df['Date'], errors='coerce')  print("\nAfter converting") print(df) 

Output
After converting         Date  Values 0 2022-01-01     100 1        NaT     200 2        NaT     300 3        NaT     400 

Explanation: This code converts various date formats in the 'Date' column to datetime using pd.to_datetime(), handling errors with errors='coerce', which replaces invalid dates with NaT.


Next Article
How to Convert String to Float in Pandas DataFrame

H

hanishj
Improve
Article Tags :
  • Python
  • Pandas
  • Python pandas-dataFrame
  • AI-ML-DS With Python
Practice Tags :
  • python

Similar Reads

  • How to Change Pandas Dataframe Datetime to Time
    The DatetimeIndex contains datetime64[ns] data type, which represents timestamps with nanosecond precision. In many cases, we may just want to extract the time component from a Pandas Datetime column or index. Let's discuss easy ways to convert the Datetime to Time data while preserving all the time
    2 min read
  • How to Convert String to Float in Pandas DataFrame
    Converting Strings to Float in Pandas DataFrame is a very crucial step for data analysis. Converting string to float values can help you perform various arithmetic operations and plot graphs. In this article, we'll look at different ways to convert a string to a float in DataFrame. Creating Sample D
    4 min read
  • How to Sort a Pandas DataFrame by Date?
    In the real world, we can come across datasets of any form that may include the date inside them too. These datasets can be present in any file format like .CSV, .xlsx, .txt, etc. To load this data inside Python, we use a library named Pandas which provides us a plethora of functions and methods to
    3 min read
  • Python | Pandas dataframe.pct_change()
    Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.pct_change() function calculates the percentage change between the cu
    2 min read
  • Pandas Convert Date (Datetime) To String Format
    Datetime is a data type in Pandas that provides a standardized way to represent and display dates and times in a human-readable format. It allows customization of output, such as displaying months, days, and years, offering flexibility in presenting temporal information. Necessity to convert Datetim
    5 min read
  • How to Convert Float to Datetime in Pandas DataFrame?
    Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to Datetime, String to Integer, Float to Datetime, etc. For converting float to DateTime we use pandas.to_datetime() function and following syntax is used : Syntax:
    3 min read
  • How to Group Pandas DataFrame By Date and Time ?
    In this article, we will discuss how to group by a dataframe on the basis of date and time in Pandas. We will see the way to group a timeseries dataframe by Year, Month, days, etc. Additionally, we'll also see the way to groupby time objects like minutes. Pandas GroupBy allows us to specify a groupb
    3 min read
  • How to rename columns in Pandas DataFrame
    In this article, we will see how to rename column in Pandas DataFrame. The simplest way to rename columns in a Pandas DataFrame is to use the rename() function. This method allows renaming specific columns by passing a dictionary, where keys are the old column names and values are the new column nam
    4 min read
  • Setting the name of the axes in Pandas DataFrame
    There are multiple operations which can be performed over the exes in Pandas. Let's see how to operate on row and column index with examples. For link to the CSV file used in the code, click here. Reset the name of the row index. Code #1 : We can reset the name of the DataFrame index by using df.ind
    2 min read
  • How to Convert Integer to Datetime in Pandas DataFrame?
    Let's discuss how to convert an Integer to Datetime in it. Now to convert Integers to Datetime in Pandas DataFrame. Syntax of  pd.to_datetimedf['DataFrame Column'] = pd.to_datetime(df['DataFrame Column'], format=specify your format)Create the DataFrame to Convert Integer to Datetime in Pandas Check
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences