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 - Return the Period object as a timestamp with minutely frequency
To return the Period object as a timestamp with minutely frequency, use the period.to_timestamp() method and set the freq parameter as 'T'.
Understanding Period and Timestamp
A pandas.Period represents a specific period of time, while a timestamp represents a specific moment. The to_timestamp() method converts periods to timestamps with different frequency resolutions.
Creating a Period Object
First, let's create a Period object with second-level precision ?
import pandas as pd
# Creating a Period object with second frequency
period = pd.Period(freq="S", year=2021, month=11, day=26, hour=11, minute=45, second=55)
print("Original Period:")
print(period)
Original Period: 2021-11-26 11:45:55
Converting to Timestamp with Minutely Frequency
Now convert the Period to a timestamp with minutely frequency using freq='T' ?
import pandas as pd
# Creating a Period object
period = pd.Period(freq="S", year=2021, month=11, day=26, hour=11, minute=45, second=55)
# Convert to timestamp with minutely frequency
timestamp = period.to_timestamp(freq='T')
print("Original Period:", period)
print("Timestamp with minutely frequency:", timestamp)
print("Type of result:", type(timestamp))
Original Period: 2021-11-26 11:45:55 Timestamp with minutely frequency: 2021-11-26 11:45:00 Type of result: <class 'pandas._libs.tslibs.timestamps.Timestamp'>
Multiple Period Examples
Here's how different periods convert to minutely timestamps ?
import pandas as pd
# Create multiple periods with different frequencies
periods = [
pd.Period('2021-11-26 11:45:55', freq='S'),
pd.Period('2021-11-26 11:45', freq='T'),
pd.Period('2021-11-26 11', freq='H')
]
print("Period to Minutely Timestamp Conversion:")
print("-" * 50)
for p in periods:
timestamp = p.to_timestamp(freq='T')
print(f"Period: {p} ? Timestamp: {timestamp}")
Period to Minutely Timestamp Conversion: -------------------------------------------------- Period: 2021-11-26 11:45:55 ? Timestamp: 2021-11-26 11:45:00 Period: 2021-11-26 11:45 ? Timestamp: 2021-11-26 11:45:00 Period: 2021-11-26 11:00 ? Timestamp: 2021-11-26 11:00:00
Key Points
- The
to_timestamp()method converts Period objects to Timestamp objects - Using
freq='T'sets the timestamp resolution to minutes - Seconds are truncated when converting to minutely frequency
- The resulting timestamp represents the beginning of the minute period
Conclusion
Use period.to_timestamp(freq='T') to convert Period objects to timestamps with minutely frequency. This truncates seconds and returns the start of the minute containing the original period.
