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 daily frequency
To return the Period object as a timestamp with daily frequency, use the period.to_timestamp() method and set the freq parameter as 'D'.
Understanding Pandas Period Objects
The pandas.Period represents a specific period of time with a defined frequency. When converted to a timestamp with daily frequency, it returns the start of that day at 00:00:00.
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("Period object:")
print(period)
Period object: 2021-11-26 11:45:55
Converting to Timestamp with Daily Frequency
The to_timestamp() method converts the Period to a Timestamp. When frequency is set to 'D' (daily), it returns the start of that day ?
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)
print("Original Period:")
print(period)
# Convert to timestamp with daily frequency
timestamp = period.to_timestamp(freq='D')
print("\nTimestamp with daily frequency:")
print(timestamp)
print("Type:", type(timestamp))
Original Period: 2021-11-26 11:45:55 Timestamp with daily frequency: 2021-11-26 00:00:00 Type: <class 'pandas._libs.tslibs.timestamps.Timestamp'>
Different Frequency Options
You can also convert to other frequencies for comparison ?
import pandas as pd
period = pd.Period(freq="S", year=2021, month=11, day=26, hour=11, minute=45, second=55)
print("Original Period:", period)
print("Daily frequency (D):", period.to_timestamp(freq='D'))
print("Hourly frequency (H):", period.to_timestamp(freq='H'))
print("Monthly frequency (M):", period.to_timestamp(freq='M'))
Original Period: 2021-11-26 11:45:55 Daily frequency (D): 2021-11-26 00:00:00 Hourly frequency (H): 2021-11-26 11:00:00 Monthly frequency (M): 2021-11-01 00:00:00
Key Points
- The
to_timestamp(freq='D')method returns the beginning of the day (00:00:00) - The original Period's time information is preserved in the date component
- Different frequencies return different levels of precision
- The result is a
pandas.Timestampobject, not a Period
Conclusion
Use period.to_timestamp(freq='D') to convert a Period object to a daily timestamp. This method returns the start of the day (00:00:00) while preserving the original date information.
