How to Convert DateTime to UNIX Timestamp

As a developer, I have spent a lot of time wrestling with clocks. Mast APIs and databases prefer “UNIX time”—the number of seconds since January 1, 1970—because it is a simple integer that avoids timezone confusion.

However, as humans, we prefer reading dates like “December 25, 2025, 10:00 AM,” which is why we use Python DateTime objects.

In this tutorial, I will show you exactly how to convert a Python DateTime object into a UNIX timestamp using several proven methods.

Use UNIX Timestamps in Python

A UNIX timestamp is universal. It represents a single point in time that doesn’t change regardless of whether you are in New York or Los Angeles.

I once worked on a Python project for a national retail chain that struggled with Daylight Saving Time shifts because they stored local strings instead of timestamps.

By converting to a UNIX timestamp in Python, you make your data easier to sort, filter, and compare across different servers and time zones.

Method 1: Use the datetime.timestamp() Method (Python 3.3+)

If you are using a modern version of Python, the timestamp() method is the easiest way to get the job done.

I use this method in almost all my new Python scripts because it is built directly into the datetime object.

from datetime import datetime

# The scheduled launch time for a tech event in San Francisco
launch_date = datetime(2025, 7, 4, 12, 0, 0)

# Converting the Python datetime object to a UNIX timestamp
unix_timestamp = launch_date.timestamp()

print(f"The UNIX timestamp for the event is: {unix_timestamp}")
# Output: The UNIX timestamp for the event is: 1751630400.0

You can see the output in the screenshot below.

python datetime to timestamp

The timestamp() method returns a float. The digits before the decimal represent the seconds, and the digits after represent the microseconds.

If you need a whole number (integer), which is common for many US-based web APIs, you can simply wrap the result in int().

Method 2: Handle Timezones with Python Aware DateTime

One mistake I see often is ignoring time zones. A “naive” DateTime object in Python assumes your local system time.

If your server is in a Virginia data center but your user is in Seattle, your timestamp will be off by three hours.

I always recommend using “aware” objects to ensure your Python timestamp conversion is accurate to UTC.

from datetime import datetime, timezone

# Current time in UTC for a cloud server log
current_utc_time = datetime.now(timezone.utc)

# Convert to UNIX timestamp
utc_timestamp = current_utc_time.timestamp()

print(f"The accurate UTC UNIX timestamp is: {int(utc_timestamp)}")

You can see the output in the screenshot below.

datetime to timestamp

Method 3: Use the time.mktime() Function

Before Python 3.3, we used the time module. I still encounter this frequently when maintaining legacy Python code for financial firms in Manhattan.

This method requires you to convert the DateTime object into a “struct_time” (a tuple of time parts) first.

import time
from datetime import datetime

# Deadline for a federal tax filing in the USA
deadline = datetime(2025, 4, 15, 23, 59, 59)

# Convert DateTime to struct_time, then to UNIX timestamp
struct_t = deadline.timetuple()
unix_time = time.mktime(struct_t)

print(f"Tax deadline UNIX timestamp: {unix_time}")

You can see the output in the screenshot below.

datetime to unix timestamp

One thing to remember is that time.mktime() always assumes the input is in your local time. Use this only if that is your specific intention.

Method 4: Use calendar.timegm() for UTC Conversion

If you have a Python timetuple but you want to ensure it is treated as UTC (not local time), calendar.timegm() is your best friend.

I used this method extensively when building a cross-border payment system where local time offsets could lead to legal disputes.

import calendar
from datetime import datetime

# Opening bell of the New York Stock Exchange in UTC
nyse_opening = datetime(2025, 1, 2, 14, 30, 0)

# Convert to UTC-based UNIX timestamp
unix_utc = calendar.timegm(nyse_opening.utctimetuple())

print(f"The UTC UNIX timestamp for the NYSE opening is: {unix_utc}")

You can see the output in the screenshot below.

python unix timestamp

This Python function is the inverse of time.gmtime(), making it a reliable choice for server-side operations.

Method 5: Convert a String Directly to a UNIX Timestamp

In real-world Python development, you often receive a date as a string from a user input or a CSV file.

You must first parse the string into a Python DateTime object before you can extract the timestamp.

from datetime import datetime

# Date string from a US-based flight booking system
date_string = "09-15-2025 08:30 PM"

# Define the format: Month-Day-Year Hour:Minute AM/PM
date_format = "%m-%d-%Y %I:%M %p"

# Parse string to Python datetime
dt_object = datetime.strptime(date_string, date_format)

# Convert to timestamp
timestamp_result = int(dt_object.timestamp())

print(f"The timestamp for your flight is: {timestamp_result}")

Handle Milliseconds and Microseconds

Most Python UNIX timestamps are returned as floats to preserve microsecond precision. However, many JavaScript-based frontends expect milliseconds.

To convert your Python timestamp to milliseconds (common in web development), simply multiply the float by 1,000.

# Converting Python timestamp to milliseconds for a React frontend
ms_timestamp = int(datetime.now().timestamp() * 1000)
print(f"Timestamp in milliseconds: {ms_timestamp}")

Common Issues and Troubleshooting

Throughout my career, I’ve seen two main issues pop up when developers convert DateTime to UNIX timestamps in Python:

  1. Local vs. UTC: If you don’t define a timezone, Python uses the server’s local time. If your server restarts in a different region, your timestamps will change. Always use UTC for database storage.
  2. Year 2038 Problem: On some older 32-bit systems, UNIX timestamps can’t go past the year 2038. Python 3 handles this well on 64-bit systems, but always check your environment.

If you see a negative number, it means your date is before January 1, 1970. This is common when dealing with historical data, like birthdates in a US Census Python script.

Summary of Python Conversion Methods

MethodBest Use CasePython Version
dt.timestamp()General purpose, modern scripts3.3+
time.mktime()Working with local time tuplesAll
calendar.timegm()Working with UTC time tuplesAll
Decimal PrecisionHigh-frequency trading/LoggingWorking with UTC tuples

In this tutorial, you learned several ways to convert a Python DateTime object into a UNIX timestamp.

For most modern applications, the built-in timestamp() method is the most efficient and readable choice. However, always be mindful of whether your source date is in UTC or local time to avoid data corruption.

If you are working on a large-scale Python project that spans multiple US states or countries, I strongly suggest standardizing all your time-based data to UTC timestamps as early as possible.

You may also like to read:

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.