How to Convert Timestamp to DateTime in Python
Jun 28, 2023
At some point in your developer journey, you’ve probably encountered working with dates and timestamps in Python. It’s essential to understand the concepts around dealing with date and time data so you can manipulate these data types the way you want.
Let’s explore what timestamps and datetimes are in python and learn how you can convert a timestamp to a datetime object.
Understanding Timestamps and Datetimes in Python
First, let’s get an overview of what timestamps and datetimes are in Python.
Timestamps in Python
A timestamp is a numeric representation of a specific point in time. It’s usually represented as the number of seconds (or sometimes milliseconds) that have elapsed since a specific reference point called the “epoch.” In Python, the epoch is commonly defined as January 1, 1970.
You might wonder why we need timestamps when we already have datetimes. Well, timestamps provide a standardized way to represent time that is independent of time zones and human-readable formats. This makes it easier to perform calculations, comparisons, and other operations involving time.
Python provides several ways to work with timestamps. One popular module is time, which provides functions like time() to get the current timestamp.
Let’s see how we can use the time module to print the current timestamp.
import time current_timestamp = time.time() print("Current Timestamp:", current_timestamp)
When you run the above code, you should see the current timestamp from the epoch of January 1, 1970 as shown below:
Current Timestamp: 1693137418.480114
Datetimes in Python
Datetimes are a type of data in Python that are used to represent dates and times together. Python has a built-in datetime module that provides classes and functions for working with date times. Datetimes store information about the year, month, day, hour, minute, second, and even microsecond.
Let’s take a look at a simple example to understand its syntax:
from datetime import datetime current_datetime = datetime.now() print("Current Datetime:", current_datetime)
The above code will print the current datetime on the screen as shown:
Current Datetime: 2023-08-27 17:43:41.666569
What Is the Difference Between Timestamp and Datetime in Python?
Timestamps can be likened to numerical coordinates on the timeline of history. They represent specific moments in time as numbers, typically counting the seconds (or sometimes milliseconds) that have passed since a reference point known as the epoch (often set to January 1, 1970). Think of timestamps as the mathematical underpinnings of time.
For instance, imagine you want to mark the dawn of the internet era in 1995. In timestamp terms, this pivotal moment is quantified by the number of seconds between 1970 and 1995.
epoch_timestamp = 0 internet_era_timestamp = 1995 - 1970
Timestamps are powerful tools for precise calculations, ideal for measuring time intervals, comparing events, and handling complex temporal operations.
In contrast, datetimes are like snapshots capturing the essence of a moment in a human-readable format. They elegantly encapsulate year, month, day, and other time elements, creating a comprehensive representation of time. Datetimes are the visual expressions of time, making them intuitive for us humans to understand and work with.
For instance, consider a hypothetical birthday: January 15, 1995. In datetime terms, this is a holistic portrayal encompassing the year, month, and day.
from datetime import datetime birthday_datetime = datetime(year=1995, month=1, day=15)
Datetimes shine in scenarios where communicating time information to users is essential. They’re perfect for calendars, event schedules, and interfaces that require a human touch.
In essence, timestamps excel behind the scenes, where precise calculations reign, while datetimes step forward to interact gracefully with humans, bringing time to life in relatable ways. Combining both timestamps and datetimes equips you with a versatile toolkit for mastering the time dimension in your programming journey.
Common Operations With Python Timestamps and Datetimes
There are various scenarios where you can use Python timestamps and datetimes. For instance, you can use them for operations such as measuring time intervals, calculating execution time, and more. Let’s look at some of these use cases and scenarios with some easy-to-understand examples.
Measuring Execution Time
You can use timestamps to measure how much time your code takes to execute. In order to do this, you can first create a starting timestamp before your code runs or executes. Then, you can run some synchronous pieces of code.
Here’s the general syntax for that:
import time start_time = time.time() # Your code here end_time = time.time() execution_time = end_time - start_time print("Execution Time:", execution_time, "seconds")
Let’s try this with a simple example:
import time start_time = time.time() for x in range(1000000000): if(x==99999999): print('Loop over!') end_time = time.time() execution_time = end_time - start_time print("Execution Time:", execution_time, "seconds")
In the above code, we run a long loop and print a message before the loop exits. Since the loop runs for a large number of iterations, this code consumes some time to execute. On my machine, the above code takes 30 seconds to execute:
Loop over! Execution Time: 30.553071975708008 seconds
This way, you can evaluate the execution time of any piece of code that might run slow, which may indicate that it’s data-intensive or performing expensive and time-consuming computations or operations.
Converting Timestamp to Datetime
Timestamps can be converted to human-readable datetime objects. This is particularly useful when you want to present time information to users. Let’s take a look at a simple example where we convert the current timestamp to a human-readable date using the fromtimestamp() method of datetime module.
from datetime import datetime import time timestamp = time.time() date_object = datetime.fromtimestamp(timestamp) print("Datetime:", date_object)
The above code should print the following output:
Datetime: 2023-08-27 17:48:18.683378
Let’s explore this use case a bit further in the next section.
Converting Timestamp to Datetime in Python
Converting a timestamp to a datetime object is a common task when dealing with time-related data. Python’s datetime module comes to the rescue with the fromtimestamp() function, which allows us to easily perform this conversion. As we’ve already seen with an example in the previous section, let’s break down each step to understand how to perform the conversion.
- Import the Required Modules Before we proceed, ensure you have the datetime module available.
from datetime import datetime
- Obtain the Timestamp Have the timestamp you want to convert ready. This could be from a dataset, API response, or any other source.
timestamp = 1629788400 # Replace with your timestamp
- Convert to Datetime Use the fromtimestamp() function to convert the timestamp to a datetime object.
dt_object = datetime.fromtimestamp(timestamp)
- Display the Result Finally, print or manipulate the converted datetime object as needed.
Now you have successfully converted a timestamp to a datetime object in Python!
print("Converted Datetime:", dt_object)
How to Convert Timestamp to Datetime in Python Pandas
While this tutorial primarily focuses on using Python’s datetime module for timestamp conversion, you might wonder about pandas. In pandas, you can achieve similar conversions using the pd.to_datetime() function. However, the principles remain quite similar. If you’re looking for pandas-specific examples, check out the pandas documentation.
Handling Time Zones and Microseconds
When working with timestamps and datetimes, it’s important to consider time zones and microsecond precision.
Time zones play a crucial role in the world of dates and times, and understanding them is essential for accurate and meaningful temporal calculations. Let’s delve into what time zones are and how they work.
Previously, we touched on converting timestamps to datetimes using the fromtimestamp() function. While this function provides the date and time in your system’s local time zone by default, you might need to consider different time zones when working with data from diverse sources.
Python’s datetime module allows you to work with time zones using the pytz library. Here’s a quick example of converting a timestamp to a datetime with a specific time zone:
from datetime import datetime import pytz timestamp = 1629788400 timezone = pytz.timezone('America/New_York') dt_object = datetime.fromtimestamp(timestamp, tz=timezone) print("Datetime with Timezone:", dt_object)
In the output below, you can see that the time zone is specified after the time:
Datetime with Timezone: 2021-08-24 03:00:00-04:00
Using time zones can help you in a lot of use cases—for instance, if you’re building a platform that connects users from various parts of the world. Your user in New York schedules an event for 3:00 PM in their local time, and another user in Tokyo does the same. As the platform owner, you must ensure that both users see the correct event time, accounting for the time difference between New York and Tokyo. It’s also helpful in showing localized time in your application to your user so every user sees the dates and times in their own time zone without any confusion.
If your timestamp includes milliseconds or microseconds, you can retain that precision during the conversion. Just make sure your timestamp is in seconds or milliseconds (not microseconds), since fromtimestamp() expects a value in seconds.
Here’s an example:
timestamp_with_micros = 1629788400.123456 # Example timestamp with microseconds dt_object_with_micros = datetime.fromtimestamp(timestamp_with_micros) print("Datetime with Microseconds:", dt_object_with_micros)
Which prints the following output:
Datetime with Microseconds: 2021-08-24 12:30:00.123456
How to Convert a Floating-Point Timestamp to Datetime in Python
Timestamps are commonly represented as floating-point numbers, especially when microsecond precision is needed. The process of converting a floating-point timestamp to a datetime is the same as demonstrated in this tutorial. Simply use the fromtimestamp() function, and Python will handle the conversion effortlessly.
In this tutorial, we’ve explored the concepts of timestamps and datetimes in Python. We learned how timestamps represent points in time, and how to use the time module to work with them. We also discussed the datetime module for dealing with human-readable datetimes.
The main focus of this tutorial was to demonstrate the process of converting a timestamp to a datetime object using the fromtimestamp() function. We walked through the steps required for this conversion and provided examples along the way. Additionally, we touched on handling time zones and microsecond precision to cover various scenarios you might encounter.
Whether you’re measuring execution time, analyzing temporal data, or simply presenting information to users, the ability to convert timestamps to datetimes is a fundamental tool in your Python toolbox. As you continue your Python journey, remember that timestamps and datetimes are essential components that empower you to work with temporal data effectively.