How to get a timestamp in Python
Learn how to get a timestamp in Python. This guide covers various methods, tips, real-world applications, and common error debugging.

A timestamp in Python is a fundamental tool. You need it to log events, track data changes, and monitor performance. Python’s modules make timestamp work precise and straightforward.
In this article, you'll explore several techniques to retrieve timestamps. You will find practical tips for implementation, see real world applications, and get advice to debug common issues with your time data.
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 your most direct route to a Unix timestamp. It calculates the number of seconds elapsed since the epoch—a standard starting point of January 1, 1970.
The function returns a floating-point number, not an integer. This fractional part represents sub-second precision, which is crucial for tasks like performance profiling or recording event sequences where milliseconds matter.
Standard timestamp approaches
While time.time() gives you a raw number, Python’s standard library offers more structured ways to work with timestamps through the time and datetime modules.
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
The time module lets you refine the raw timestamp. You can convert the float from time.time() into a whole number using int(), which simply drops the milliseconds. For a more human-friendly format, you can combine two functions:
time.localtime()converts the epoch seconds into a structured time object for your local timezone.time.strftime()then formats that object into a readable string based on the codes you provide, like%Yfor the year.
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 provides a more object-oriented way to work with time. Instead of a raw number, datetime.now() returns a datetime object that packages the current date and time together, making it more intuitive to handle.
- This object contains detailed attributes you can access directly, such as
.year,.month, and.day. - To get a standard Unix timestamp, you simply call the
datetime.timestamp()method on the object.
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 you're handling time data. You'll often need to convert a raw Unix timestamp—perhaps from a database or an API call—into a more versatile datetime object.
- The
datetime.fromtimestamp()method is the bridge between these two formats. It takes a float timestamp as its argument. - In return, you get a complete
datetimeobject. This allows you to easily extract specific details like the day or hour, or perform date-based arithmetic.
Advanced timestamp techniques
For more complex applications, you'll need to go beyond simple timestamps to manage timezones, achieve higher precision, and work with standardized 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 operates across different regions, naive timestamps can cause confusion. A timezone-aware timestamp includes offset information, making it unambiguous. Python’s datetime module makes this straightforward.
- To get the current time in Coordinated Universal Time (UTC), you pass
timezone.utcto thedatetime.now()function. This creates an “aware” object. - Calling
datetime.now()without any arguments gives you a “naive” object representing your system’s local time, which lacks timezone data.
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
When you need to measure performance, time.perf_counter() is your best option. It's designed specifically for timing short durations with high accuracy. The value it returns isn't a timestamp of the current time of day; it's just a point from a high-resolution clock.
- Because its starting point is arbitrary, you only use the difference between two calls—like
end - start—to find the elapsed time. - This function is ideal for benchmarking code snippets because it provides the highest precision your system can offer.
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
When you need to represent a timestamp as a string, Python gives you powerful options for standardization and customization. This is essential for tasks like logging, creating filenames, or sending data to an API.
- The
.isoformat()method is your go-to for a universal standard. It generates a string in the ISO 8601 format, which is widely understood by other programs and systems. - For complete control, you can use
.strftime(). It lets you build a custom string by passing in format codes—like%Yfor the year—allowing you to create unique formats for specific needs.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. You can describe what you want to build, and its AI capabilities help you create it, from simple scripts to full-stack apps.
With the timestamp techniques you've learned, Replit Agent can turn those concepts into production-ready tools. It builds complete applications with databases, APIs, and deployment directly from your descriptions.
- Build a timezone converter that takes a Unix timestamp and displays the local time for multiple cities around the world.
- Create a performance dashboard that uses
perf_counter()to benchmark different sorting algorithms and visualizes the results. - Deploy an event logging utility that automatically generates log files with ISO 8601 formatted timestamps for every entry.
Describe your next project, and Replit Agent writes the code, tests it, and gets it running for you, all within your browser.
Common errors and challenges
Working with timestamps can introduce tricky bugs, but most have straightforward solutions once you know what to look for.
Troubleshooting timestamp comparison errors
A common pitfall is trying to compare a timezone-aware datetime object with a naive one. Python will raise a TypeError because it can't logically compare a specific moment in time with one that lacks timezone context. To fix this, you must make both objects either aware or naive before the comparison.
Fixing string parsing errors with datetime.strptime()
When converting a string to a datetime object, you might encounter a ValueError from the datetime.strptime() function. This almost always means the format code you provided doesn't perfectly match the input string. Ensure every character, from separators like slashes to the number of digits, aligns with your format string.
Handling timezone confusion in timestamps
Timezone confusion is a frequent source of subtle bugs. This happens when your application misinterprets a timestamp—for example, treating a UTC time from a server as if it were the user's local time. The best defense is to standardize on UTC for all internal logic and storage. You should only convert to a local timezone at the last moment, right before displaying the time to a user.
Troubleshooting timestamp comparison errors
Troubleshooting timestamp comparison errors
You can't directly compare a datetime object with a numeric timestamp from time.time(). Python doesn't know how to handle these different data types together, which results in a TypeError. The following code demonstrates this common mistake.
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 > operator fails because it's trying to compare two different things: a structured datetime object and a raw number. To make the comparison work, they must be in the same format. The corrected approach is shown below.
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")
The fix is to convert the datetime object into a numeric timestamp before making a comparison. By calling now_datetime.timestamp(), you transform the object into a float that matches the format from time.time(). With both values as numbers, the > operator works as expected, and the TypeError is resolved. Keep an eye out for this issue when you're working with values from both the time and datetime modules in the same logic.
Fixing string parsing errors with datetime.strptime()
Fixing string parsing errors with datetime.strptime()
When you convert a string to a datetime object using datetime.strptime(), the function is unforgiving. Forgetting the format string argument is a common oversight that will stop your code with a TypeError before it even gets to check the date.
Take a look at the following example, where the missing second argument causes the program to fail.
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}")
The strptime() function requires a format string to know how to interpret the date. Without this second argument, Python can't make sense of the string's structure. The corrected code below provides this missing piece.
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}")
The fix is simple: you must provide strptime() with a format string that matches your date string's structure. In this case, "%Y-%m-%d %H:%M:%S" tells Python exactly how to read the year, month, day, and time.
Without it, the function doesn't know how to parse the text, leading to a TypeError. This error often pops up when you're processing date strings from external sources like APIs or log files.
Handling timezone confusion in timestamps
Handling timezone confusion in timestamps
Timezone issues are a common source of bugs. When you create a timestamp with time.time() and convert it using datetime.fromtimestamp(), the resulting object is "naive"—it has no timezone info. This can lead to incorrect time displays. The code below 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 dt object implicitly uses the system's local timezone. This is unreliable for applications with a global user base, as it can display the wrong time. The corrected code below shows how to handle this properly.
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}")
The fix is to make your datetime objects "aware" by explicitly setting a timezone. When converting a timestamp with datetime.fromtimestamp(), pass tz=timezone.utc as an argument. This creates an unambiguous object that isn't tied to the system's local time.
- This is crucial for applications that operate across different regions.
- It ensures timestamps are interpreted correctly and prevents you from mixing up server and user timezones.
Real-world applications
Now that you can navigate common timestamp pitfalls, you can apply these techniques to build practical tools for logging and performance monitoring.
Creating a simple event logger with datetime
You can put these timestamp skills to work by building a simple event logger that pairs a formatted string from datetime with each event message.
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 creates a simple, timestamped record for application events. It captures the current moment with datetime.now() and then uses the strftime() method to format it into a clean, human-readable string.
- The function combines this formatted timestamp with the event message you provide.
- Each call to
log_event()prints a new line, creating a chronological log of operations like "Application started" or "User login successful."
This approach is a foundational technique for tracking activity in any script or application.
Measuring database query performance with time.time()
By capturing a timestamp with time.time() before and after a database call, you can calculate the exact duration and identify performance bottlenecks.
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 code offers a straightforward method for measuring how long a function runs. The simulate_database_query function captures a start time, pauses with time.sleep() to imitate a workload, and then returns the difference between the end and start times.
- It effectively brackets an operation with two calls to
time.time(). - Subtracting the initial timestamp from the final one gives you the total elapsed time as a float.
- You can adapt this pattern to measure the execution speed of any part of your code.
Get started with Replit
Turn your knowledge into a tool. Tell Replit Agent to "build a script that renames photos with their creation timestamp" or "create a web app that calculates the days between two dates."
Replit Agent writes the code, tests for errors, and deploys your app, turning your prompt into a finished product. Start building with Replit.
Create and 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.
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.



.png)