How to get a timestamp in Python

Your guide to getting timestamps in Python. Learn different methods, see real-world examples, and find solutions to common errors.

How to get a timestamp in Python
Published on: 
Tue
Mar 3, 2026
Updated on: 
Wed
Apr 1, 2026
The Replit Team

A timestamp in Python is essential to log events, track data changes, or measure performance. Python’s built-in modules provide simple and powerful ways to handle time-related tasks.

In this article, you'll discover several techniques to get timestamps, from basic to advanced. You will find practical implementation tips, explore real-world applications, and get straightforward advice to debug common issues.

Using time.time() for basic timestamp

import time
timestamp = time.time()
print(f"Current timestamp: {timestamp}")--OUTPUT--Current timestamp: 1698761542.345678

The time.time() function is the most direct way to get a numeric timestamp. It returns a floating-point number representing the seconds passed since the Unix epoch—midnight on January 1, 1970. This format is a universal standard, making it ideal for time-difference calculations and logging events in a system-agnostic way.

Because it’s a float, you get sub-second precision from the fractional part of the number. This level of detail is essential for tasks like performance profiling where milliseconds can make all the difference.

Standard timestamp approaches

While time.time() gives you a raw number, you'll often need more structured timestamp formats, which Python’s time and datetime modules readily provide.

Using time module timestamp functions

import time
timestamp_seconds = int(time.time())
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(f"Seconds since epoch: {timestamp_seconds}\nFormatted: {formatted_time}")--OUTPUT--Seconds since epoch: 1698761542
Formatted: 2023-10-31 12:45:42

To get a clean, whole-second timestamp, you can simply cast the result of time.time() to an integer with int(). When you need a more readable format, the time module provides a flexible solution.

  • The time.localtime() function converts the standard epoch time into a time structure based on your system's local timezone.
  • You then pass this structure to time.strftime(). This function uses format codes like %Y for year and %d for day to create a customized string.

Working with datetime.now()

from datetime import datetime
now = datetime.now()
timestamp = datetime.timestamp(now)
print(f"Current datetime: {now}\nAs timestamp: {timestamp}")--OUTPUT--Current datetime: 2023-10-31 12:45:42.345678
As timestamp: 1698761542.345678

The datetime module offers a more object-oriented approach. Calling datetime.now() returns a rich datetime object that bundles the current local date and time together. This is often more intuitive than a raw number, as the object contains accessible attributes for the year, month, day, and more.

  • You can easily manipulate individual time components directly from the object.
  • To get a standard numeric timestamp, simply pass the object to datetime.timestamp(), which converts it back to seconds since the epoch.

Converting between timestamp formats

import time
from datetime import datetime
timestamp = time.time()
dt_object = datetime.fromtimestamp(timestamp)
print(f"Unix timestamp: {timestamp}\nDatetime object: {dt_object}")--OUTPUT--Unix timestamp: 1698761542.345678
Datetime object: 2023-10-31 12:45:42.345678

Flexibility is key when working with time, and you'll often need to switch between formats. You can easily turn a numeric Unix timestamp back into a feature-rich datetime object. This is useful when you've stored a timestamp and later need to display it in a readable format or perform date-specific calculations.

  • The datetime.fromtimestamp() method is your tool for this, taking the numeric timestamp as its argument.

This approach gives you the efficiency of a numeric timestamp for storage and the flexibility of a datetime object for manipulation.

Advanced timestamp techniques

For more complex needs, Python provides advanced tools for handling timezones, capturing high-precision timing with perf_counter(), and creating standardized timestamp formats.

Working with timezone-aware timestamps

from datetime import datetime, timezone
utc_now = datetime.now(timezone.utc)
local_now = datetime.now()
print(f"UTC time: {utc_now}\nLocal time: {local_now}")--OUTPUT--UTC time: 2023-10-31 10:45:42.345678+00:00
Local time: 2023-10-31 12:45:42.345678

When your application handles data from different locations, a simple timestamp isn't enough. A "naive" datetime object from datetime.now() lacks timezone information, which can lead to confusion. To solve this, you create a "timezone-aware" object that includes an offset from a standard reference.

  • Passing timezone.utc to datetime.now() generates a timestamp explicitly set to Coordinated Universal Time (UTC), the global standard for timekeeping.
  • This ensures your timestamps are consistent and unambiguous, no matter where your code or users are located.

High-precision timing with perf_counter()

import time
start = time.perf_counter()
# Simulate operation
time.sleep(0.1)
end = time.perf_counter()
print(f"Operation took {end - start:.9f} seconds")--OUTPUT--Operation took 0.100123456 seconds

For measuring performance, time.perf_counter() is your most reliable tool. It provides access to a high-resolution monotonic clock, which is ideal for calculating short time intervals with great accuracy. This makes it perfect for benchmarking code.

  • The clock used by perf_counter() is monotonic, meaning it only ever moves forward. This prevents issues if the system's time is adjusted.
  • The value returned is arbitrary. You should only use the difference between consecutive calls to measure elapsed time, as shown in the example.

ISO 8601 and custom timestamp formats

from datetime import datetime
now = datetime.now()
iso_format = now.isoformat()
custom_format = now.strftime("%Y%m%d_%H%M%S_%f")
print(f"ISO format: {iso_format}\nCustom format: {custom_format}")--OUTPUT--ISO format: 2023-10-31T12:45:42.345678
Custom format: 20231031_124542_345678

For consistent timestamps across different systems, you'll want a standard format. The datetime object gives you powerful and simple ways to format your timestamp strings.

  • The isoformat() method provides a string in the ISO 8601 format. This is a universal standard, making it perfect for APIs and exchanging data.
  • When you need full control, strftime() lets you build a completely custom format. This is ideal for creating things like unique, timestamped filenames.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. Describe what you want to build, and Agent 4 handles everything—from writing the code and connecting APIs to deploying it live.

Instead of piecing together techniques, you can describe the complete app you want to build and let Agent take it from idea to a working product:

  • A timestamp converter that takes a Unix timestamp and displays it in multiple timezone-aware, human-readable formats.
  • A performance logging utility that uses perf_counter() to benchmark function execution times and saves the results with ISO 8601 timestamps.
  • An event scheduler that lets users input dates in a local format and stores them as standardized UTC timestamps for a backend system.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Working with timestamps can introduce tricky bugs, but most are easy to fix once you know what to look for.

Troubleshooting timestamp comparison errors

A common source of errors is trying to compare different types of timestamps directly. Python will raise a TypeError if you try to compare a "naive" datetime object (which has no timezone information) with a timezone-"aware" one. They aren't equivalent, and the comparison is blocked to prevent subtle bugs.

  • To fix this, you need to make both objects either naive or aware before comparing them.
  • Similarly, you can't directly compare a numeric timestamp from time.time() with a datetime object. You must first convert one to match the other's format, ensuring a consistent basis for comparison.

Fixing string parsing errors with datetime.strptime()

When you convert a string into a datetime object using datetime.strptime(), you might run into a ValueError. This almost always means the format code you provided doesn't perfectly match the input string. The function is very strict about this.

For example, if your string is "2023/10/31" but your format is "%Y-%m-%d", the function will fail because it expects hyphens, not slashes. To resolve this, carefully check that your format string is an exact template of the date string, including all separators and the order of elements.

Handling timezone confusion in timestamps

Timezone issues can cause some of the most confusing bugs, often leading to data being off by several hours. This happens when different parts of your system make different assumptions—one part might use the server's local time while another uses UTC. Without a clear standard, it's easy to store or calculate times incorrectly.

The most robust solution is to standardize on a single timezone, usually UTC, for all internal logic and storage. You should convert all incoming timestamps to UTC immediately and only convert them to a user's local time for display purposes right before showing it to them. This creates a reliable single source of truth for time across your application.

Troubleshooting timestamp comparison errors

Comparing a datetime object with a numeric timestamp from time.time() will result in a TypeError. Since they're different data types, Python can't perform a direct comparison using an operator like >. The code below shows exactly what happens.

from datetime import datetime
import time

now_datetime = datetime.now()
now_timestamp = time.time()

# This will raise TypeError
if now_datetime > now_timestamp:
print("Datetime is greater")

The TypeError happens because the > operator doesn't know how to compare a datetime object with a numeric float. They are different types. The code below shows the correct way to perform this comparison.

from datetime import datetime
import time

now_datetime = datetime.now()
now_timestamp = time.time()

# Convert to same type for comparison
if now_datetime.timestamp() > now_timestamp:
print("Datetime is greater")

To fix the TypeError, you must convert both values to the same format before the comparison. The solution is to call the .timestamp() method on the datetime object, which turns it into a numeric timestamp just like the one from time.time(). The comparison then works because you're comparing two numbers. This error often appears when you mix different time-tracking methods, like storing a start time and an end time using different functions.

Fixing string parsing errors with datetime.strptime()

The strictness of datetime.strptime() often causes a ValueError when the format string doesn't perfectly mirror the date string. Even a small mismatch will cause the conversion to fail. The following code shows a common mistake that triggers this error.

from datetime import datetime

date_string = "2023-10-31 12:45:42"
# Missing format string will cause error
timestamp = datetime.strptime(date_string).timestamp()
print(f"Timestamp: {timestamp}")

This code triggers an error because datetime.strptime() is missing its required second argument. It needs a format string to know how to parse the date. The corrected code below shows the proper way to call it.

from datetime import datetime

date_string = "2023-10-31 12:45:42"
# Correctly specify the format string
timestamp = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S").timestamp()
print(f"Timestamp: {timestamp}")

To fix the ValueError, you must supply datetime.strptime() with its required second argument—a format string. The format "%Y-%m-%d %H:%M:%S" perfectly matches the input date_string, telling Python exactly how to interpret the string for a successful conversion. This error often appears when parsing dates from external files or APIs, so always ensure your format string matches the source data precisely.

Handling timezone confusion in timestamps

Timezone issues are notoriously tricky, causing silent bugs where timestamps are off by hours. This often happens when combining time.time() with datetime.fromtimestamp(), as the code implicitly assumes the system's local timezone, leading to ambiguity. The following code demonstrates this problem.

from datetime import datetime
import time

# This assumes local timezone but doesn't make it explicit
timestamp = time.time()
dt = datetime.fromtimestamp(timestamp)
print(f"Current time: {dt}")

The resulting datetime object is "naive"—it has no timezone context, making it ambiguous and prone to errors. The code below shows the proper way to create a timezone-aware object for reliable, cross-system timekeeping.

from datetime import datetime, timezone
import time

timestamp = time.time()
# Explicitly specify timezone
utc_time = datetime.fromtimestamp(timestamp, tz=timezone.utc)
local_time = datetime.fromtimestamp(timestamp)
print(f"UTC time: {utc_time}\nLocal time: {local_time}")

To fix timezone ambiguity, you must create an "aware" datetime object. The solution is to explicitly pass a timezone, like tz=timezone.utc, to the datetime.fromtimestamp() method. This anchors the timestamp to a universal standard instead of the local system's time. This practice is crucial for applications handling data across different regions, ensuring your timestamps are always consistent and correct. It prevents silent bugs where time appears to shift unexpectedly.

Real-world applications

Moving beyond troubleshooting, you can apply Python’s timestamp functions to practical tasks like event logging and performance measurement.

Creating a simple event logger with datetime

You can create a straightforward event logger by combining datetime.now() with strftime() to produce consistently formatted, human-readable timestamps for every log entry.

from datetime import datetime

def log_event(event_name):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{timestamp}] {event_name}")

log_event("Application started")
log_event("User login successful")

This log_event function encapsulates the timestamping logic, making your logging consistent and reusable. It works by:

  • Capturing the current moment with datetime.now().
  • Formatting it into a clean "YYYY-MM-DD HH:MM:SS" string using strftime().

This standardization is key for creating logs that are easy for both humans and machines to parse. By printing the timestamp with the event message, you get a clear, chronological record of your application's activity.

Measuring database query performance with time.time()

You can easily benchmark database performance by capturing a timestamp with time.time() before and after a query runs, then calculating the difference.

import time

def simulate_database_query(query_type):
start_time = time.time()
# Simulate different query times
time.sleep(0.1 if query_type == "simple" else 0.3)
return time.time() - start_time

simple_time = simulate_database_query("simple")
complex_time = simulate_database_query("complex")
print(f"Simple query: {simple_time:.4f}s, Complex query: {complex_time:.4f}s")

This function, simulate_database_query, returns the exact time an operation took to complete. It works by saving a start_time with time.time(). After the simulated task finishes, it calls time.time() again.

  • The function’s return value is the second timestamp minus the first.
  • This result represents the total elapsed seconds as a floating-point number.

This pattern is a straightforward way to measure how long any piece of code takes to execute.

Get started with Replit

Put your new skills to use. Tell Replit Agent to build “a tool that converts Unix timestamps to multiple timezones” or “a performance dashboard that benchmarks functions and logs results with ISO 8601 timestamps.”

The Agent writes the code, tests for errors, and deploys your app from a simple description. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.