Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Pandas - Construct a naive UTC datetime from a POSIX timestamp
To construct a naive UTC datetime from a POSIX timestamp, use the pd.Timestamp.utcfromtimestamp() method. A POSIX timestamp represents the number of seconds since January 1, 1970, 00:00:00 UTC.
What is a POSIX Timestamp?
A POSIX timestamp (also called Unix timestamp) is the number of seconds that have elapsed since the Unix epoch (January 1, 1970, 00:00:00 UTC). It's a standard way to represent time across different systems.
Basic Syntax
pd.Timestamp.utcfromtimestamp(posix_timestamp)
Example
Let's create a Pandas timestamp and use it to construct a naive UTC datetime from a POSIX timestamp ?
import pandas as pd
# Creating a timestamp
timestamp = pd.Timestamp('2021-09-14T15:12:34.261811624')
# Display the original timestamp
print("Original Timestamp:")
print(timestamp)
# Constructing a naive UTC datetime from a POSIX timestamp
# The POSIX timestamp 1631717502 represents a specific moment in time
utc_datetime = timestamp.utcfromtimestamp(1631717502)
print("\nUTC Datetime from POSIX timestamp:")
print(utc_datetime)
Original Timestamp: 2021-09-14 15:12:34.261811624 UTC Datetime from POSIX timestamp: 2021-09-15 14:51:42
Understanding the Process
The method converts the POSIX timestamp (1631717502 seconds) into a human-readable datetime format. Note that the result is a "naive" datetime, meaning it doesn't contain timezone information but represents UTC time.
Working with Current POSIX Timestamp
You can also get the current POSIX timestamp and convert it ?
import pandas as pd
import time
# Get current POSIX timestamp
current_posix = int(time.time())
print(f"Current POSIX timestamp: {current_posix}")
# Convert to UTC datetime
current_utc = pd.Timestamp.utcfromtimestamp(current_posix)
print(f"Current UTC datetime: {current_utc}")
Current POSIX timestamp: 1631717502 Current UTC datetime: 2021-09-15 14:51:42
Conclusion
Use pd.Timestamp.utcfromtimestamp() to convert POSIX timestamps to naive UTC datetime objects. This is useful when working with timestamp data from different systems or APIs that provide time in POSIX format.
