Movatterモバイル変換


[0]ホーム

URL:


Python Pandas Tutorial

Python Pandas - Time Span Representation



Pandas provides thePeriod object to represent time spans, also known as regular intervals of time, such as days, months, or years. This is particularly useful when working with time series data that focuses on time periods rather than exact timestamps.

In this tutorial, we will learn about the basics of working with Period objects in Pandas, including how to create and manipulate them, perform arithmetic operations, convert them to Timestamp objects, and obtain formatted string representations.

The Period Object

ThePeriod object in Pandas represents a fixed time span (a period of time), such as a month, a quarter, or a day. You can define the span of a period using thefreq parameter, which is set with a frequency alias like "D" for days, "M" for months, or "Y" for years.

Creating aPeriod object in Pandas can be done by using thepandas.Period() class.

Syntax

Following is the syntax of the Period class−

class pandas.Period(value=None, freq=None, ordinal=None, year=None, month=None, quarter=None, day=None, hour=None, minute=None, second=None)

Example: Creating the Period object

Here is an example of creating the Period object for different frequencies using thepandas.Period() class.

import pandas as pd# Creating Period objects with different frequencies# Yearly frequency p1 = pd.Period("2024", freq="Y")  # Daily frequencyp2 = pd.Period("2024-01-01", freq="D") # Hourly frequencyp3 = pd.Period("2024-01-01 19:00", freq="H")print("Output Yearly frequency:", p1)print("Output Daily frequency:", p2)print("Output Hourly frequency:", p3)

On executing the above code you will get the following output −

Output Yearly frequency: 2024Output Daily frequency: 2024-01-01Output Hourly frequency: 2024-01-01 19:00

Arithmetic with Period Objects

PandasPeriod object support arithmetic operations, like addition and subtraction, based on their defined frequency. You can add or subtract integers from a Period to shift it to that own frequency. Note that arithmetic operations between different frequencies are not allowed.

Example

The following example demonstrates applying the arithmetic operations toPeriod object with integers.

import pandas as pd# Creating Period objects with different frequencies# Yearly frequency p1 = pd.Period("2024", freq="Y")  # Daily frequencyp2 = pd.Period("2024-01-01", freq="D") # Hourly frequencyp3 = pd.Period("2024-01-01 19:00", freq="H")# Adding and subtracting intervalsprint("2024+1 =", p1 + 1) print("2024 - 3 =", p1 - 3) print("2024-01-01 + 2 =", p2 + 2) print("2024-01-01 - 2 =", p2 - 2) print("2024-01-01 19:00 + 4 =", p3 + 4) print("2024-01-01 19:00 - 3 =", p3 - 3)

Following is the output of the above code −

2024+1 = 20252024 - 3 = 20212024-01-01 + 2 = 2024-01-032024-01-01 - 2 = 2023-12-302024-01-01 19:00 + 4 = 2024-01-01 23:002024-01-01 19:00 - 3 = 2024-01-01 16:00

Combining Periods with Time Offsets

If aPeriod frequency is daily or higher (e.g., hourly, minute, seconds, etc.), you can add time offsets, such aspd.offsets.Hour(2) ordatetime.timedelta objects to the Period.

Example

This example demonstrates combining time offsets with aPeriod object.

import pandas as pdfrom datetime import timedeltaimport numpy as np# Create a period objectp = pd.Period("2024-11-01 09:00", freq="H")# Adding hours using different timedelta like objectsprint(p + pd.offsets.Hour(2)) print(p + timedelta(minutes=120)) print(p + np.timedelta64(7200, "s"))

Following is the output of the above code −

2024-11-01 11:002024-11-01 11:002024-11-01 11:00

Note: you will get theIncompatibleFrequency error, if you try to add a time offset which results can have the different frequency.

Converting a Period Object to a String

Thepandas.Period() class provides thestrftime() method to convert aperiod object to a string representation, with custom formatting based on date and time directives.

Example

This example demonstrates the process of formatting and retrieving the string representation of the Period object using thePeriod.strftime() method.

import pandas as pdperiod = pd.Period(freq="S", year=2024, month=11, day=5, hour=8, minute=20, second=45)print("Period:", period)# Period object to String representation with specific formatprint("Formatted String:", period.strftime('%d-%b-%Y'))# Using multiple formatting directivesprint("Detailed Format:", period.strftime('%b. %d, %Y was a %A'))

Following is the output of the above code −

Period: 2024-11-05 08:20:45Formatted String: 05-Nov-2024Detailed Format: Nov. 05, 2024 was a Tuesday

Convert Period Object to Timestamp

Thepandas.Period() class provides theto_timestamp() method to convertperiod object totimestamp with the specified frequencies.

Example: Basic Period Object Conversion to Timestamp

Here is the basic example of using thepandas.Period.to_timestamp() method to convertperiod object totimestamp object.

import pandas as pdperiod = pd.Period(freq="S", year=2024, month=11, day=5, hour=8, minute=20, second=45)print("Period:", period)# Convert to Timestampprint("Converted to Timestamp:", period.to_timestamp(freq='T'))

Following is the output of the above code −

Period: 2024-11-05 08:20:45Converted to Timestamp: 2024-11-05 08:20:00

Example: Period to Timestamp Conversion with Daily Frequency

This example shows how to convert aPeriod object to aTimestamp with Daily Frequency.

import pandas as pdperiod = pd.Period(freq="S", year=2024, month=11, day=5, hour=8, minute=20, second=45)print("Period:", period)# Convert to daily frequency Timestampprint("Daily Timestamp:", period.to_timestamp(freq='D'))

Following is the output of the above code −

Period: 2024-11-05 08:20:45Daily Timestamp: 2024-11-05 00:00:00

Example: Conversion with Minutely Frequency

Here is another example of converting the Period object to Timestamp with minutely frequency.

import pandas as pdperiod = pd.Period(freq="S", year=2024, month=11, day=5, hour=8, minute=20, second=45)print("Period:", period)# Convert to minutely frequency Timestampprint("Minutely Timestamp:", period.to_timestamp(freq='T'))

Following is the output of the above code −

Period: 2024-11-05 08:20:45Minutely Timestamp: 2024-11-05 08:20:00
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp