How to Convert Integer to Datetime in Pandas DataFrame?
Last Updated :
03 Oct, 2022
Improve
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_datetime
df['DataFrame Column'] = pd.to_datetime(df['DataFrame Column'], format=specify your format)
Create the DataFrame to Convert Integer to Datetime in Pandas
Check data type for the 'Dates' column is Integer.
# importing pandas package
import pandas as pd
# creating a dataframe
values = {'Dates': [20190902, 20190913, 20190921],
'Attendance': ['Attended', 'Not Attended', 'Attended']
}
df = pd.DataFrame(values, columns=['Dates', 'Attendance'])
# display
print(df)
print(df.dtypes)
Output:

Example 1:
Now to convert it into Datetime we use the previously mentioned syntax. Since in this example the date format is yyyymmdd, the date format can be represented as follows:
format= '%Y%m%d'
# importing pandas package
import pandas as pd
# creating the dataframe
values = {'Dates': [20190902, 20190913, 20190921],
'Attendance': ['Attended', 'Not Attended', 'Attended']
}
df = pd.DataFrame(values, columns=['Dates', 'Attendance'])
# converting the integers to datetime format
df['Dates'] = pd.to_datetime(df['Dates'], format='%Y%m%d')
# display
print(df)
print(df.dtypes)
Output:

Example 2:
Now, suppose the Pandas DataFrame has a date in the format yymmdd. In this case, the date format would now contain 'y' in lowercase:
format='%y%m%d'
# importing pandas package
import pandas as pd
# creating dataframe
values = {'Dates': [190902, 190913, 190921],
'Attendance': ['Attended', 'Not Attended', 'Attended']
}
df = pd.DataFrame(values, columns=['Dates', 'Attendance'])
# changing the integer dates to datetime format
df['Dates'] = pd.to_datetime(df['Dates'], format='%y%m%d')
# display
print(df)
print(df.dtypes)
Output:

Example 3:
Now, let's suppose that your integers contain both date and time. In that case, the format that you should specify is:
format='%Y%m%d%H%M%S'
# importing pandas package
import pandas as pd
# creating dataframe
values = {'Dates': [20190902093000, 20190913093000, 20190921200000],
'Attendance': ['Attended', 'Not Attended', 'Attended']
}
df = pd.DataFrame(values, columns=['Dates', 'Attendance'])
# changing integer values to datetime format
df['Dates'] = pd.to_datetime(df['Dates'], format='%Y%m%d%H%M%S')
# display
print(df)
print(df.dtypes)
Output:

Example 4:
Consider this DataFrame with microseconds in our DateTime values. In this case, the format should be specified as:
format='%Y%m%d%H%M%S%F'
# importing pandas package
import pandas as pd
# creating dataframe
values = {'Dates': [20190902093000912, 20190913093000444,
20190921200000009],
'Attendance': ['Attended', 'Not Attended', 'Attended']
}
df = pd.DataFrame(values, columns=['Dates', 'Attendance'])
# changing the integer dates to datetime format
df['Dates'] = pd.to_datetime(df['Dates'], format='%Y%m%d%H%M%S%F')
# display
print(df)
print(df.dtypes)
Output:
