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
Selected Reading
Python Pandas - Convert given Timestamp to Period
To convert a given Timestamp to Period in Pandas, use the timestamp.to_period() method. The freq parameter sets the frequency for the period conversion.
Syntax
timestamp.to_period(freq=None)
Parameters
freq ? Frequency string (e.g., 'D' for daily, 'M' for monthly, 'Y' for yearly)
Basic Example
Here's how to convert a timestamp to a monthly period ?
import pandas as pd
# Create a timestamp object
timestamp = pd.Timestamp('2021-09-14T15:12:34.261811624')
# Display the original timestamp
print("Original Timestamp:")
print(timestamp)
# Convert timestamp to monthly period
monthly_period = timestamp.to_period(freq='M')
print("\nConverted to Monthly Period:")
print(monthly_period)
Original Timestamp: 2021-09-14 15:12:34.261811624 Converted to Monthly Period: 2021-09
Different Frequency Options
You can use various frequency strings for different period types ?
import pandas as pd
timestamp = pd.Timestamp('2021-09-14T15:12:34')
# Different frequency conversions
daily = timestamp.to_period(freq='D')
weekly = timestamp.to_period(freq='W')
monthly = timestamp.to_period(freq='M')
quarterly = timestamp.to_period(freq='Q')
yearly = timestamp.to_period(freq='Y')
print("Daily Period:", daily)
print("Weekly Period:", weekly)
print("Monthly Period:", monthly)
print("Quarterly Period:", quarterly)
print("Yearly Period:", yearly)
Daily Period: 2021-09-14 Weekly Period: 2021-09-12/2021-09-18 Monthly Period: 2021-09 Quarterly Period: 2021Q3 Yearly Period: 2021
Common Frequency Codes
| Frequency Code | Description | Example Output |
|---|---|---|
| 'D' | Daily | 2021-09-14 |
| 'W' | Weekly | 2021-09-12/2021-09-18 |
| 'M' | Monthly | 2021-09 |
| 'Q' | Quarterly | 2021Q3 |
| 'Y' | Yearly | 2021 |
Conclusion
The to_period() method converts timestamps to periods with specified frequency. Use appropriate frequency codes like 'D', 'M', 'Q', or 'Y' to group timestamps into meaningful time periods for analysis.
Advertisements
