Change an Integer to a Datetime Object in Python

While I was working on a data analysis project where I needed to convert Unix timestamps (stored as integers) to readable datetime objects. The challenge was that these integers represented time in different formats, some were Unix timestamps in seconds, others in milliseconds, and some were just date representations like 20231105 for November 5, 2023.

In this article, I’ll share multiple ways to convert integers to datetime objects in Python. Whether you’re working with Unix timestamps or custom integer date formats, I’ve got you covered.

So let’s get in!

Conversion of Integer to Datetime

Let me show you the methods to convert int to datetime in Python.

Method 1: Use datetime.fromtimestamp() for Unix Timestamps

The most common scenario is converting a Unix timestamp (seconds since January 1, 1970) to a datetime object:

from datetime import datetime

# Unix timestamp (seconds since Jan 1, 1970)
timestamp = 1636329600  # November 8, 2021

# Convert to datetime
date_time = datetime.fromtimestamp(timestamp)
print(date_time)

Output

2021-11-08 05:30:00

You can refer to the screenshot below to see the output

python convert int to datetime

This method works great for standard Unix timestamps in seconds, which is what most systems use.

Read Fix “Function Not Implemented for This Dtype” Error in Python

Method 2: Convert Millisecond Timestamps

If your integer represents milliseconds since the Unix epoch (common in JavaScript and some databases):

from datetime import datetime

# Unix timestamp in milliseconds
timestamp_ms = 1636329600000  # Same date as above, but in milliseconds

# Convert to datetime by dividing by 1000
date_time = datetime.fromtimestamp(timestamp_ms / 1000)
print(date_time)  

Output

2021-11-08 05:30:00

You can refer to the screenshot below to see the output

pandas convert int to datetime

The key here is dividing by 1000 to convert milliseconds to seconds before using fromtimestamp().

Check out Read a CSV to the dictionary using Pandas in Python

Method 3: Convert Date Integers (YYYYMMDD)

Sometimes integers represent dates in formats like YYYYMMDD. Here’s how to handle that:

from datetime import datetime

# Integer in YYYYMMDD format
date_int = 20231105  # November 5, 2023

# Convert to string first, then parse
date_str = str(date_int)
date_time = datetime.strptime(date_str, '%Y%m%d')
print(date_time)

Output

2023-11-05 00:00:00

You can refer to the screenshot below to see the output

convert int to datetime python

This method is useful when dealing with date integers that aren’t timestamps but direct date representations.

Method 4: Use pandas for Batch Conversions

If you’re working with large datasets, pandas provides efficient tools for conversion:

import pandas as pd

# List of Unix timestamps
timestamps = [1636329600, 1636416000, 1636502400]  # Nov 8, 9, 10, 2021

# Convert using pandas
dates = pd.to_datetime(timestamps, unit='s')
print(dates)
# DatetimeIndex(['2021-11-08', '2021-11-09', '2021-11-10'], dtype='datetime64[ns]', freq=None)

This is particularly useful when you need to convert multiple values at once.

Advanced Conversions and Edge Cases

Now. I will explain some advanced conversions and edge cases with respect conversion of int to datetime.

Read Python Dataframe Update Column Value

Handle Timezone Information

By default, the fromtimestamp() method in Python uses your local timezone. For UTC:

from datetime import datetime, timezone

timestamp = 1636329600
# Convert to UTC datetime
utc_time = datetime.fromtimestamp(timestamp, tz=timezone.utc)
print(utc_time)  # 2021-11-08 00:00:00+00:00

Convert Dates with Time Components

For integers that include both date and time (like YYYYMMDDHHMMSS):

from datetime import datetime

# Integer representing 2023-11-05 13:45:30
datetime_int = 20231105134530

# Convert to string and parse
datetime_str = str(datetime_int)
date_time = datetime.strptime(datetime_str, '%Y%m%d%H%M%S')
print(date_time)  # 2023-11-05 13:45:30

This technique can be adapted for any integer date format as long as you can define a consistent parsing pattern.

Handle Invalid Timestamps

Error handling is important when working with potentially invalid data:

from datetime import datetime

def safe_timestamp_to_datetime(timestamp):
    try:
        return datetime.fromtimestamp(timestamp)
    except (ValueError, OSError, OverflowError):
        print(f"Invalid timestamp: {timestamp}")
        return None

# Test with valid and invalid timestamps
print(safe_timestamp_to_datetime(1636329600))  # Works fine
print(safe_timestamp_to_datetime(-62135596800))  # May cause issues on some systems

Real-World Application: Analyze Sales Data

Let’s see a practical example. Say you have sales data with timestamps stored as integers:

import pandas as pd
from datetime import datetime

# Sample sales data with Unix timestamps
sales_data = [
    {"transaction_id": 1001, "amount": 125.99, "timestamp": 1635734400},  # Nov 1, 2021
    {"transaction_id": 1002, "amount": 89.95, "timestamp": 1635820800},   # Nov 2, 2021
    {"transaction_id": 1003, "amount": 45.50, "timestamp": 1635907200},   # Nov 3, 2021
    {"transaction_id": 1004, "amount": 250.00, "timestamp": 1635993600},  # Nov 4, 2021
]

# Create DataFrame
df = pd.DataFrame(sales_data)

# Convert timestamps to datetime
df['date'] = pd.to_datetime(df['timestamp'], unit='s')

# Extract just the date part for grouping
df['sale_date'] = df['date'].dt.date

# Group by date and sum the amounts
daily_sales = df.groupby('sale_date')['amount'].sum()

print(daily_sales)

This converts integer timestamps to readable dates, allowing you to analyze sales trends by date.

Performance Considerations

If you’re converting large numbers of integers to datetime objects, performance matters:

  1. Pandas is fastest for bulk operations – Use pd.to_datetime() for large datasets
  2. Caching results – If you repeatedly convert the same values, consider caching
  3. Use the right precision – Don’t use millisecond methods for second timestamps

I hope you found this article helpful. The methods that I have explained in this article are: using datetime.fromtimestamp() for Unix timestamp, converting millisecond timestamp, converting date integers, and using pandas for batch conversions.

I also discussed some advanced conversions and edge cases, along with handling invalid timestamps and real-world applications.

Other Python articles you may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.