Working with Timestamps in Python

In Python, timestamps are commonly represented using the Unix timestamp format. The Unix timestamp is a way to track time as a running total of seconds. This count starts at the Unix Epoch on January 1st, 1970, at 00:00:00 Coordinated Universal Time (UTC). Thus, the Unix timestamp is simply the number of seconds that have elapsed between a specific date and the Unix Epoch.

The advantage of Unix timestamps is that they offer a standardized, unambiguous way to represent a moment in time, regardless of your location on Earth. This makes them extremely useful for computer systems that need to track and organize dated information in dynamic and distributed applications, both online and on the client side.

This tutorial covers the essentials of working with timestamps in Python. You’ll learn how to obtain the current timestamp, convert between datetime objects and timestamps, customize timestamp formatting, and handle timestamps that use milliseconds for higher precision.

Python Modules for Handling Timestamps

In Python, the datetime and time modules are primarily used to work with timestamps.

  • datetime: The datetime module is one of the most important modules for handling dates and times in Python. It offers classes like datetime, date, time, timedelta, and timezone, allowing for the manipulation of dates, times, and intervals.
  • time: The time module complements the datetime module by providing functions that interact with the system’s time. It’s useful for tasks like obtaining the current UNIX time (in seconds since the Epoch), pausing the execution of a program for a specified duration, and other time-related operations.

Getting the Current Timestamp

In Python, there are two primary methods for obtaining the current timestamp, both of which provide the number of seconds that have elapsed since the Unix epoch (January 1st, 1970, at 00:00:00 UTC) with high precision.

Using the datetime Module

The first one involves the datetime module. You start by getting the current local date and time as a datetime object with the datetime.now() method. Then, apply the timestamp() method to this object to convert it into a Unix timestamp.

from datetime import datetime

# Get current datetime object
current_datetime = datetime.now()

# Convert datetime object to timestamp
current_timestamp = current_datetime.timestamp()
print("Current Timestamp:", current_timestamp)
# Current Timestamp: 1709624677.911529

Using the time Module

Alternatively, you can use the time module’s time() method, which offers a more straightforward approach. Unlike the datetime module, the time() method directly returns the current time as a Unix timestamp.

import time

current_timestamp = time.time()
print("Current Timestamp:", current_timestamp)
# Current Timestamp: 1709624677.911529

Converting datetime Objects to Timestamps

To create a timestamp for a specific date and time, you can instantiate a datetime object by specifying the year, month, day, hour, minute, second, and microsecond. Then, convert this object into a timestamp using the timestamp() method.

from datetime import datetime

# Create a datetime object
datetime_object = datetime(year=2024, month=3, day=1, hour=15, minute=30)

# Convert datetime object to timestamp
timestamp = datetime_object.timestamp()
print("Current Timestamp:", timestamp)
# Current Timestamp: 1709287200.0

Converting Timestamps to datetime Objects

If you have a timestamp and want to convert it back into a datetime object, the datetime module offers the fromtimestamp() method specifically for this purpose.

To use it, simply pass your timestamp to the fromtimestamp() method. It will return a datetime object representing the date and time that corresponds to the timestamp.

from datetime import datetime

# Example timestamp
timestamp = 1677888200

# Convert timestamp to datetime object
datetime_object = datetime.fromtimestamp(timestamp)
print(datetime_object)
# Output: 2023-03-04 05:33:20

Formatting a Timestamp as a Date-time String

Timestamps in their raw form aren’t designed for easy human interpretation. To make them more readable, you first convert the timestamp into a datetime object using the fromtimestamp() method, and then format this datetime object into a string by using the strftime() method.

The strftime() method allows you to customize the formatting of the timestamp. You provide format codes (e.g., %Y for year, %d for day, %B for full month name) to specify the desired output.

from datetime import datetime

# Example timestamp
timestamp = 1677888200

# Convert timestamp to datetime object
datetime_object = datetime.fromtimestamp(timestamp)

# Format the datetime object
formatted_string = datetime_object.strftime("%B %d, %Y %H:%M:%S")
print(formatted_string)
# Output: March 04, 2023 05:33:20

There are various formatting options available, which you can explore in our exclusive guide!

Converting a Date-Time String into a Timestamp

If you have a date-time string, you can easily convert it into a timestamp.

First, use the strptime() method from the datetime module to parse the date-time string into a datetime object. This step requires you to provide a format string that matches the way your date and time are arranged within your input string. Then, convert the datetime object to a timestamp using the timestamp() method.

from datetime import datetime

# Your date-time string
datetime_string = "2024-03-01 15:30:00"

# Parse the string into a datetime object
datetime_object = datetime.strptime(datetime_string, "%Y-%m-%d %H:%M:%S")

# Convert datetime object to timestamp
timestamp = datetime_object.timestamp()
print("Timestamp:", timestamp)
# Output: Timestamp: 1709287200.0

Obtaining Timestamps in Milliseconds

Unix timestamps usually represent time in seconds. However, there are situations like logging, performance tracking, or working with APIs where you might need higher precision – down to milliseconds (ms).

To get a timestamp in milliseconds in Python, you can take the timestamp in seconds (obtained from either datetime.now().timestamp() or time.time()) and multiply it by 1000. This conversion will give you the equivalent timestamp expressed in milliseconds since the Epoch.

from datetime import datetime
import time

# Using datetime.now().timestamp()
current_time = datetime.now()
timestamp_ms = current_time.timestamp() * 1000
print("Timestamp in milliseconds:", timestamp_ms)
# Output: 1709645009397.592

# Using time.time()
timestamp_ms = time.time() * 1000
print("Timestamp in milliseconds:", timestamp_ms)
# Output: 1709645009397.592

Timezone Considerations

Python’s datetime objects can be classified into two categories: naive and aware. A naive datetime object doesn’t include any information about time zones. Whereas, a timezone-aware datetime object explicitly carries time zone information, meaning it knows its offset from UTC.

When you use the timestamp() method on a datetime object to convert it to a Unix timestamp:

  • If the datetime object is naive, it is treated as if it were in the local timezone.
  • If the datetime object is timezone-aware, the timestamp() method takes timezone information into account before calculating the timestamp. This ensures that the timestamp accurately reflects the universal moment in time, regardless of the local timezone.

So it’s important to understand the difference between naive and timezone-aware datetime objects when working with timestamps, especially if your application deals with dates and times across multiple timezones. Incorrect handling of timezones can result in errors in how time is interpreted and compared.

Let’s illustrate this with an example. The code below demonstrates how Python handles timestamps for both naive and timezone-aware datetime objects.

from datetime import datetime, timezone

# Naive datetime 
naive_dt = datetime(2024, 3, 6, 10, 0)  

# Timezone aware datetime (UTC)
utc_dt = datetime(2024, 3, 6, 10, 0, tzinfo=timezone.utc) 

naive_timestamp = naive_dt.timestamp()
utc_timestamp = utc_dt.timestamp()

print("Naive Timestamp:", naive_timestamp)  # Output: 1709699400.0
print("UTC Timestamp:", utc_timestamp)      # Output: 1709719200.0

The code prints two timestamps. The naive timestamp reflects your local timezone’s offset from UTC, while the UTC timestamp is directly based on Coordinated Universal Time.