Pandas convert string to datetime
In this post, you will learn how to convert a string format to a datetime format using the Python Pandas. Pandas is a Python library that is basically used for data analysis.
In any programming language, datetime is a common datatype. Date and Time are often written in strings or any other format that we should convert into a single format. In data science time series projects, it is common practice to convert strings to datetime objects. Python pandas contains a feature for working with date and time. Here, we have mentioned how to convert a dataframe column of strings to a datatime format using Python Pandas inbuilt function pd.to_datetime().
Syntax of pd.to_datetime()
pandas.to_datetime(arg, errors=’raise’, dayfirst=False, yearfirst=False,
utc=None, box=True, format=None, exact=True, unit=None,
infer_datetime_format=False, origin=’unix’, cache=False)
- arg: An integer, string, float, list or dict object to convert into a DateTime object.
- dayfirst: Boolean value, True if the input contains the day first
- yearfirst: Boolean value, True if the input contains the year first.
- utc: Boolean value, Returns the UTC Datetime Index if True.
- format: the position of the day, month, and year in the date.
Pandas convert date string to datetime
In the given Python program, we have converted a string to a date format.
import pandas as pd
# input in mm.dd.yyyy format
date = ['06.10.2020']
# output in yyyy-mm-dd format
print(pd.to_datetime(date))
Output of the above code-
DatetimeIndex(['2020-06-10'], dtype='datetime64[ns]', freq=None)
Pandas convert data and time string to datetime
In the given Python program, we have converted a date and time string to a datetime format.
import pandas as pd
# date (mm.dd.yyyy) and time (H:MM:SS)
date = ['11.02.2020 5:50:10 PM']
# output in yyyy-mm-dd HH:MM:SS
print(pd.to_datetime(date))
Output of the above code:
DatetimeIndex(['2020-11-02 17:50:10'], dtype='datetime64[ns]', freq=None)
Convert Strings to Datetime in Pandas DataFrame
In the given Python program, we have mentioned a step-by-step process to convert Pandas DataFrame column type from string to datetime format. Suppose we have the following data and we want to convert strings to datetime in Pandas DataFrame.
Name | DOB |
Ankita | 20110413 |
Somya | 20020113 |
Tanya | 20050713 |
Kanika | 20100113 |
Create the dataframe
Here, we have created a DataFrame from the above data.
import pandas as pd
values = {'Name': ['Ankita', 'Somya', 'Tanya', 'Kanika'],
'DOB': ['20110413', '20020113', '20050713', '20100113']
}
df = pd.DataFrame(values, columns = ['Name','DOB'])
print (df)
print (df.dtypes)
Output of the above code:
Name DOB
0 Ankita 20110413
1 Somya 20020113
2 Tanya 20050713
3 Kanika 20100113
Name object
DOB object
dtype: object
Convert the Strings to Datetime in the DataFrame
import pandas as pd
values = {'Name': ['Ankita', 'Somya', 'Tanya', 'Kanika'],
'DOB': ['20110413', '20020113', '20050713', '20100113']
}
df = pd.DataFrame(values, columns = ['Name','DOB'])
df['DOB'] = pd.to_datetime(df['DOB'], format='%Y%m%d')
print (df)
print (df.dtypes)
Output of the above code-
Name DOB
0 Ankita 2011-04-13
1 Somya 2002-01-13
2 Tanya 2005-07-13
3 Kanika 2010-01-13
Name object
DOB datetime64[ns]
dtype: object
Related Articles
Python convert dataframe to numpy arrayWrite Python Pandas Dataframe to CSV
Python Pandas DataFrame
Python program to list even and odd numbers of a list
Convert List to Dataframe Python
Sort list in descending order Python
Convert array to list Python
Python take screenshot of specific window
Web scraping Python BeautifulSoup
Convert dictionary to dataframe Python
Python program to add two numbers
Print new line python
Python Spell Checker Program
Python remove punctuation from string
How to convert Excel to CSV Python Pandas
How to read data from excel file using Python Pandas
How to read data from excel file in Python
Python read JSON from URL requests
Python send mail to multiple recipients using SMTP server
How to generate QR Code in Python using PyQRCode
Python programs to check Palindrome strings and numbers
CRUD operations in Python using MYSQL Connector
Fibonacci Series Program in Python
Python File Handler - Create, Read, Write, Access, Lock File
Python convert XML to JSON
Python convert xml to dict
Python convert dict to xml