To convert integers to datetime in Pandas DataFrame:
df["DataFrame Column"] = pd.to_datetime(df["DataFrame Column"], format=specify format)
Note that the integers must match the format specified.
The Examples
Example 1: Date format of “YYYYMMDD“
To start with a simple example, create a DataFrame with a column called “dates” that contains integers (with a format of YYYYMMDD):
import pandas as pd
data = {"dates": [20240305, 20240316, 20240328],
"status": ["open", "open", "close"]
}
df = pd.DataFrame(data)
print(df)
print(df.dtypes)
As you can see, the data type is integer for the values under the “dates” column:
dates status
0 20240305 open
1 20240316 open
2 20240328 close
dates int64
status object
dtype: object
The date format of YYYYMMDD can be represented as follows (refer to the following source for the different formats):
format='%Y%m%d'
Therefore, the complete code to convert the integers to datetime would be:
import pandas as pd
data = {"dates": [20240305, 20240316, 20240328],
"status": ["open", "open", "close"]
}
df = pd.DataFrame(data)
df["dates"] = pd.to_datetime(df["dates"], format="%Y%m%d")
print(df)
print(df.dtypes)
Run the code in Python, and you’ll see that the data type for the ‘dates‘ column is now datetime:
dates status
0 2024-03-05 open
1 2024-03-16 open
2 2024-03-28 close
dates datetime64[ns]
status object
dtype: object
Example 2: Date format of “YYMMDD“
Now assume that the dates are formatted as YYMMDD:
import pandas as pd
data = {"dates": [240305, 240316, 240328],
"status": ["open", "open", "close"]
}
df = pd.DataFrame(data)
print(df)
print(df.dtypes)
As you can see, the data type is integer as well:
dates status
0 240305 open
1 240316 open
2 240328 close
dates int64
status object
dtype: object
The required date format to represent YYMMDD is therefore:
format="%y%m%d"
So the complete Python code is:
import pandas as pd
data = {"dates": [240305, 240316, 240328],
"status": ["open", "open", "close"]
}
df = pd.DataFrame(data)
df["dates"] = pd.to_datetime(df["dates"], format="%y%m%d")
print(df)
print(df.dtypes)
As before, the integers would be converted to datetime:
dates status
0 2024-03-05 open
1 2024-03-16 open
2 2024-03-28 close
dates datetime64[ns]
status object
dtype: object
Example 3: Date format of “YYYYMMDDHHMMSS”
In that case, the format that you’ll need to specify is:
format="%Y%m%d%H%M%S"
So the full Python code would be:
import pandas as pd
data = {
"dates": [20240305093000, 20240316093000, 20240328200000],
"status": ["open", "open", "closed"],
}
df = pd.DataFrame(data)
df["dates"] = pd.to_datetime(df["dates"], format="%Y%m%d%H%M%S")
print(df)
print(df.dtypes)
You’ll now get the datetime format:
dates status
0 2024-03-05 09:30:00 open
1 2024-03-16 09:30:00 open
2 2024-03-28 20:00:00 closed
dates datetime64[ns]
status object
dtype: object
Check the following guide for the steps to convert strings to datetime in Pandas DataFrame.