5 Best Ways to Convert Unix Time to Datetime in Python

πŸ’‘ Problem Formulation: When working with timestamps in Python, you may encounter Unix epoch time, which represents the time in seconds since January 1, 1970. The challenge is to convert this integer value into a human-readable datetime format. For example, converting the Unix time 1618359143 into its equivalent datetime object or string representation.

Method 1: Using the datetime Module

This method involves using the fromtimestamp() method from Python’s built-in datetime module. This is a straightforward and commonly used approach to convert Unix time to a datetime object in Python. The functionality is robust and handles time zones.

Here’s an example:

from datetime import datetime

timestamp = 1618359143
dt_object = datetime.fromtimestamp(timestamp)
print(dt_object)

Output: 2021-04-13 22:19:03

This code snippet converts the timestamp to a datetime object using datetime.fromtimestamp() and prints the result as a datetime string. It automatically uses the system’s local timezone.

Method 2: Using the time Module

The time module in Python provides the localtime() method, which can be used to convert Unix time to a time.struct_time object in local time. This method is part of Python’s standard library and is a low-level alternative to the datetime module.

Here’s an example:

import time

timestamp = 1618359143
time_obj = time.localtime(timestamp)
print(time.strftime("%Y-%m-%d %H:%M:%S", time_obj))

Output: 2021-04-13 22:19:03

By first converting the Unix time to a struct_time object, you can then format it into a string using time.strftime().

Method 3: Using the pandas Library

For those who work with data analysis in Python, the pandas library provides the to_datetime() function. This is convenient when working with sequences or data structures that require conversion of multiple Unix timestamps simultaneously.

Here’s an example:

import pandas as pd

timestamp = 1618359143
dt_object = pd.to_datetime(timestamp, unit='s')
print(dt_object)

Output: 2021-04-13 22:19:03

By passing the Unix timestamp to the to_datetime() function with the unit ‘s’ (for seconds), pandas returns a Timestamp object that can be manipulated within pandas data structures or converted to a string.

Method 4: Using the arrow Library

Another library that provides a clean, human-friendly approach to date and time manipulation is arrow. This library can be used to quickly convert Unix time to a datetime object and is praised for its simplicity and usability.

Here’s an example:

import arrow

timestamp = 1618359143
dt_object = arrow.get(timestamp)
print(dt_object)

Output: 2021-04-13T22:19:03+00:00

arrow.get() is used to convert the timestamp to an arrow object, which automatically uses UTC time. The result can easily be formatted or converted to other time zones using arrow‘s methods.

Bonus One-Liner Method 5: Using List Comprehension with datetime

For those who prefer a compact, Pythonic way of converting multiple Unix timestamps, this one-liner using list comprehension and the datetime module is quite handy.

Here’s an example:

from datetime import datetime

timestamps = [1618359143, 1618362800]
dt_objects = [datetime.fromtimestamp(ts) for ts in timestamps]
print(dt_objects)

Output: [datetime.datetime(2021, 4, 13, 22, 19, 3), datetime.datetime(2021, 4, 13, 23, 20)]

Using a list comprehension, the code converts a list of Unix timestamps to a list of datetime objects. It’s a clean and efficient way to handle multiple conversions in one line of code.

Summary/Discussion

  • Method 1: datetime.fromtimestamp(). Convert single Unix timestamp to local datetime object. Robust and easy to use. Comes with Python’s standard library.
  • Method 2: time.localtime(). Converts to struct_time object in local time. Suitable for simple conversions. A low-level approach.
  • Method 3: pandas.to_datetime(). Ideal for converting Unix timestamps within a pandas DataFrame. Integrates with data analysis workflows. Requires pandas installation.
  • Method 4: arrow.get(). Easy-to-read syntax for conversion and manipulation. Automatically uses UTC. Requires installation of the arrow package.
  • Method 5: List comprehension with datetime. Pythonic and compact for processing lists of timestamps. Great for inline conversions.