Convert Integer to Datetime in Pandas DataFrame
This post will help you learn how to convert integer to DateTime in Pandas dataframe in Python. Our purpose is to perform this particular task using the Pandas.Datetime()
method. Therefore, before we begin to work on this task, we have to ensure that the integer data conform to the specified format by using Pandas.Datetime()
method. Here are some examples given, so read the tutorial very carefully to clear all your concepts regarding the conversion of integer to datatime in Pandas in dataframe in Python.
Example 1:
# import the pandas library import pandas as pd # create adata framee values = {'Dates': [20190917, 20190923, 20190924], 'Attendance': ['Present', 'Absent', 'Present'] } #use pd.Dataframe df = pd.DataFrame(values, columns=['Dates', 'Attendance']) # print print(df) print(df.dtypes)
Output:
As you can see above in the code given the first step is to import the pandas module, then create a dataframe of values and use pd.Dataframe
method for the conversion and at last print the values.
Example 2:
Let’s examine another example where an integer contains both a date and a time. This case requires the format to be specified, so we’ll use format=’%Y%m%d%H%M%S’. Look at the code given below:
# import the pandas module import pandas as pd # create the dataframe values = {'Dates': [20190905093000, 20190908093000, 20190901200000], 'Availability': ['Available', 'Not Available', 'Available'] } #use pd.Dataframe method df = pd.DataFrame(values, columns=['Dates', 'Availability']) # change the integer values to datetime format df['Dates'] = pd.to_datetime(df['Dates'], format='%Y%m%d%H%M%S') # print print(df) print(df.dtypes)
Output:
Here in this example, you can see that the first step is to import the pandas package or module of Python. Then create the dataframe which contains the date and time values and the format in this case, should be specified first. Use pd.Dataframe
method for the conversion of integer values and change the integer values to datatime format then, at last, the print the dataframe.
Leave a Reply