How to Convert Int to Datetime in Python Pandas DataFrame [6 ways]

Are you interested in knowing different ways to convert int to datetime in Python? In this Pandas article, I will tell you six different ways to convert int to datetime in Python Pandas dataframe with the help of some examples.

To convert integers to datetime in Python’s pandas DataFrame, we can use various methods like pd.to_datetime() with different format specifiers, or convert Unix timestamps directly. applying lambda functions with apply() or changing integers to strings using astype() are also viable.

Int to datetime in Python Pandas DataFrame

Here is the list of all the ways to convert int to datetime in the Python Pandas dataframe:

  1. Using pd.to_datetime() function
  2. Using apply() with Lambda Function
  3. Changing to String with astype()
  4. Using Different Format Specifier in pd.to_datetime()
  5. Converting Unix Timestamps
  6. Full Timestamp Conversion

Let’s see them one by one using some illustrative examples:

1. Convert int to datetime Python using pd.to_datetime() function

The Pandas to_datetime() function converts an entire column of integers to datetime format in Python. The format parameter is specified to match the integer format, enabling a straightforward, column-wide conversion.

Here is the uses the to_datetime() function to convert int to datetime in Python Pandas DataFrame:

import pandas as pd

events = {
    'Event': ['Concert', 'Parade', 'Festival'],
    'City': ['New York', 'Los Angeles', 'Chicago'],
    'EventDate': [20220704, 20221111, 20230505]  # Dates in YYYYMMDD
}
df = pd.DataFrame(events)
df['EventDate'] = pd.to_datetime(df['EventDate'], format='%Y%m%d')
print(df)

Output:

      Event         City  EventDate
0   Concert     New York 2022-07-04
1    Parade  Los Angeles 2022-11-11
2  Festival      Chicago 2023-05-05

The following screenshot illustrates the result after executing the code in the Pycharm editor.

How to Convert int to datetime in Python Pandas DataFrame

2. Int to datetime Python using apply() with a lambda function

This approach applies a lambda function to each row of the Pandas DataFrame using apply() in Python. The lambda function converts each integer to a string, and then to datetime.

Here is the example, of converting int to datetime in Python Pandas DataFrame using apply() with a lambda function.

import pandas as pd

authors = {
    'Name': ['Mark Twain', 'Emily Dickinson', 'Ernest Hemingway'],
    'BirthDate': [18351130, 18301210, 18990721]  # Dates in YYYYMMDD
}
df = pd.DataFrame(authors)
df['BirthDate'] = df['BirthDate'].apply(lambda x: pd.to_datetime(str(x), format='%Y%m%d'))
print(df)

Output:

               Name  BirthDate
0        Mark Twain 1835-11-30
1   Emily Dickinson 1830-12-10
2  Ernest Hemingway 1899-07-21

After the code was implemented in the Pycharm editor, the subsequent screenshot was taken to illustrate the output.

int to date python

3. Python int to date in a DataFrame using astype() function

In this method, the entire column is first converted to string type using astype(str) in Python. Then, pd.to_datetime() is used to convert these strings to datetime.

Let’s see an example of converting int to datetime in Python Pandas DataFrame using the astype(str) function:

import pandas as pd

holidays = {
    'Holiday': ['Independence Day', 'Thanksgiving', 'Christmas'],
    'Date': [20220704, 20221124, 20221225]  # Dates in YYYYMMDD
}
df = pd.DataFrame(holidays)
df['Date'] = pd.to_datetime(df['Date'].astype(str), format='%Y%m%d')
print(df)

Output:

            Holiday       Date
0  Independence Day 2022-07-04
1      Thanksgiving 2022-11-24
2         Christmas 2022-12-25

The screenshot below features the output, taken after executing the code in the Pycharm editor.

pandas convert integer to datetime in Python

4. Pandas convert int to date using different format specifiers in to_datetime()

This method also employs the pd.to_datetime() function in Python, but with different format specifiers to match different integer formats. It’s crucial when the date format in integers varies, like having two-digit or four-digit years.

Here is the code that uses the pd.to_datetime() function with different format specifiers to convert int to datetime in the Python Pandas DataFrame.

import pandas as pd

events = {
    'Event': ['Thanksgiving Day Parade', 'Black Friday Sale', 'New Year Eve Celebration'],
    'City': ['New York', 'Los Angeles', 'Chicago'],
    'EventDate': [231123, 231124, 231231]  # Dates in YYMMDD
}
df = pd.DataFrame(events)
df['EventDate'] = pd.to_datetime(df['EventDate'], format='%y%m%d')
print(df)

Output:

                      Event         City  EventDate
0   Thanksgiving Day Parade     New York 2023-11-23
1         Black Friday Sale  Los Angeles 2023-11-24
2  New Year Eve Celebration      Chicago 2023-12-31

The screenshot below presents the output after the code was successfully implemented in the Pycharm editor.

python convert number to date

5. Convert integer to date Python with Unix timestamps

Unix timestamps are integers representing time as the number of seconds since the Unix epoch (January 1, 1970). This conversion is achieved using the pd.to_datetime() function in Python, where the unit parameter is set to ‘s’ to indicate that the integers are in seconds.

Here is the code, to convert int to datetime in Python Pandas DataFrame with Unix timestamps:

import pandas as pd

timestamps = [1609459200, 1612137600, 1614556800]
df = pd.DataFrame({'Unix Timestamp': timestamps})
df['Datetime'] = pd.to_datetime(df['Unix Timestamp'], unit='s')
print(df)

Output:

   Unix Timestamp   Datetime
0      1609459200 2021-01-01
1      1612137600 2021-02-01
2      1614556800 2021-03-01

Upon executing the code in Pycharm, the resulting output is displayed in the screenshot below.

int to datetime in dataframe in Python

6. Pandas int to datetime with full timestamp

This approach attempts to convert the integers to a full timestamp including date and time(year, month, day, hour, minute, second), requiring a more specific format specifier to match the detailed structure of the data in Python.

However, since our data only contains year, month, and day, this format specifier doesn’t match our data and would lead to incorrect conversions or errors.

Here is the code, to convert int to datetime in Python Pandas DataFrame with full timestamps:

import pandas as pd

launches = {
    'Mission': ['Apollo 11', 'STS-1', 'Voyager 2'],
    'LaunchDateTime': [196907161332, 198104121200, 197708201429]  # Dates in YYYYMMDDHHMM
}
df = pd.DataFrame(launches)
df['LaunchDateTime'] = pd.to_datetime(df['LaunchDateTime'], format='%Y%m%d%H%M')
print(df)

Output:

     Mission      LaunchDateTime
0  Apollo 11 1969-07-16 13:32:00
1      STS-1 1981-04-12 12:00:00
2  Voyager 2 1977-08-20 14:29:00

Below, a screenshot is provided, captured after the code was implemented in the Pycharm editor.

python convert int to datetime

Conclusion

Understanding the various methods such as pd.to_datetime(), using apply() with a lambda function, changing to string with astype(), employing different format specifiers in pd.to_datetime(), converting Unix timestamps, and executing full timestamp conversion is essential to convert int to datetime in Python pandas DataFrame.

Each technique offers a tailored approach to handle specific integer date representations.

You may also like to read: