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:
Convert column type from string to datetime format in Pandas dataframe
Next article icon

Pandas Convert Date (Datetime) To String Format

Last Updated : 11 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Datetime to String

It is sometimes necessary to convert a date to a specific string format in data analysis.

  • While presenting and visualizing the data for good understanding, the datetime is converted to a specific string format.
  • When exporting the data into external applications, it is sometimes necessary to convert the datetime into a string format for the compatibility and consistency of the external application.
  • Converting datetime to strings allows us to perform various operations, such as concatenation, pattern matching, slicing and other string-based operations that can be used for data preprocessing.

What is a string?

A string is a sequence of alphabets, numbers, and other characters. It is a primitive data type in Python. It is immutable; once created, it cannot be changed. The number of characters in the string is known as the length of the string.

Now we will look into a few methods that help us convert datetime into a string representation.

1. astype() method:

Pandas provides us with astype() method to convert datetime column to string format. It is a method used to convert entire data type of a column from one type to another.

Python
# importing pandas as pd import pandas as pd  # Create data with fields 'Date','Sales','Profit' data = {     'Date': pd.to_datetime(['2024-01-01', '2024-01-02', '2024-01-03']),     'Sales': [101, 201, 301],     'Profit': [909, 1809, 2709] } # Converting the data into dataframe by using pandas df = pd.DataFrame(data) print("Before conversion type:", type(df["Date"][0]))  # Using astype() method to convert 'Date' column values to Strings df['Date'] = df['Date'].astype(str) print("After conversion type:", type(df['Date'][0])) 

Output:

Before conversion type: <class 'pandas._libs.tslibs.timestamps.Timestamp'>
After conversion type: <class 'str'>

Datetime in pandas is represented by timestamp datatype. Now applying astype() method on the date column converts the date type into string. The type() method is used to know the data type of the entry. We can see the 'Date' column is converted into String representation from the timestamp datatype.

2. strftime() method:

The strftime() method, which formats a timestamp object according to a specified string format.

Python
#importing pandas as pd import pandas as pd  data = {     'Date': pd.to_datetime(['2024-01-01', '2024-01-02', '2024-01-03']),     'Sales': [101, 201, 301],     'Profit': [909, 1809, 2709] }  df = pd.DataFrame(data)  #Using dt.strftime() method by passing the specific string format as an argument. df['Date'] = df['Date'].dt.strftime('%d-%m-%Y') print(df) df.info() 

Output:

         Date  Sales  Profit
0 01-01-2024 101 909
1 02-01-2024 201 1809
2 03-01-2024 301 2709
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Date 3 non-null object
1 Sales 3 non-null int64
2 Profit 3 non-null int64

Here, with dt.strftime() method we can pass a specific format as an argument in which we want to convert our date into. We use format specifiers like '%d' ,'%m','%Y' to pass the required format as an argument.

Conclusion:

In conclusion, we can convert date (datetime) to string format by using astype() and strftime() methods in pandas. The astype() method converts the entire date-time column into an object like String. It's a simple and straightforward method but lacks the flexibility to customize the date format. While strftime() is a powerful method than astype() method. It takes the specific string format as an argument and offers us with the flexibility to convert into a specific string format.


Next Article
Convert column type from string to datetime format in Pandas dataframe

S

sairampadala811
Improve
Article Tags :
  • Geeks Premier League
  • Pandas
  • Geeks Premier League 2023

Similar Reads

  • How to Convert Datetime to Date in Pandas ?
    DateTime is a collection of dates and times in the format of "yyyy-mm-dd HH:MM:SS" where yyyy-mm-dd is referred to as the date and HH:MM:SS is referred to as Time. In this article, we are going to discuss converting DateTime to date in pandas. For that, we will extract the only date from DateTime us
    4 min read
  • How to Convert String to Date or Datetime in Polars
    When working with data, particularly in CSV files or databases, it's common to find dates stored as strings. If we're using Polars, a fast and efficient DataFrame library written in Rust (with Python bindings), we'll often need to convert these strings into actual date or datetime objects for easier
    5 min read
  • Convert column type from string to datetime format in Pandas dataframe
    To perform time-series operations, dates should be in the correct format. Let's learn how to convert a Pandas DataFrame column of strings to datetime format. Pandas Convert Column To DateTime using pd.to_datetime()pd.to_datetime() function in Pandas is the most effective way to handle this conversio
    5 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 d
    2 min read
  • Convert Date To Datetime In Python
    When you're programming, dealing with dates and times is important, and Python provides tools to manage them well. This article is about changing dates into date times in Python. We'll explore methods that can help you switch between these two types of data. Whether you're building a website or work
    3 min read
  • How to convert datetime to date in Python
    In this article, we are going to see how to convert DateTime to date in Python. For this, we will use the strptime() method and Pandas module. This method is used to create a DateTime object from a string. Then we will extract the date from the DateTime object using the date() function and dt.date f
    3 min read
  • Change String To Date In Pandas Dataframe
    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.
    5 min read
  • Python - Convert excel serial date to datetime
    This article will discuss the conversion of an excel serial date to DateTime in Python.  The Excel "serial date" format is actually the number of days since 1900-01-00 i.e., January 1st, 1900. For example, the excel serial date number 43831 represents January 1st, 2020, and after converting 43831 to
    3 min read
  • Create Python Datetime from string
    In this article, we are going to see how to create a python DateTime object from a given string. For this, we will use the datetime.strptime() method. The strptime() method returns a DateTime object corresponding to date_string, parsed according to the format string given by the user. Syntax:  datet
    4 min read
  • 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
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