Python | Pandas DatetimeIndex.snap()
Last Updated :
24 Dec, 2018
Improve
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas
Python3
Output :
Now we want to convert the given DatetimeIndex object timestamp values to the nearest frequency based on the input.
Python3
Output :
As we can see in the output, the function has snapped each timestamp value in the given DatetimeIndex object.
Example #2: Use
Python3
Output :
Now we want to convert the given DatetimeIndex object timestamp values to the nearest frequency based on the input.
Python3
Output :
As we can see in the output, the function has snapped each timestamp value in the given DatetimeIndex object.
DatetimeIndex.snap()
function is used to snap time stamps to nearest occurring frequency. The function takes a single parameter which is the frequency that we want to be applied while snapping the timestamp values of the DatetimeIndex object.
Syntax: DatetimeIndex.snap(freq) Parameters : freq : frequency Return : DatetimeIndexExample #1: Use
DatetimeIndex.snap()
function to convert the given DatetimeIndex object to the nearest occurring frequency based on the input frequency.
# importing pandas as pd
import pandas as pd
# Create the DatetimeIndex
# Here 'Q' represents quarter end frequency
didx = pd.DatetimeIndex(start ='2000-01-15 08:00', freq ='Q',
periods = 4, tz ='Asia/Calcutta')
# Print the DatetimeIndex
print(didx)

# snap the timestamp to the nearest frequency
didx.snap('MS')

DatetimeIndex.snap()
function to convert the given DatetimeIndex object to the nearest occurring frequency based on the input frequency.
# importing pandas as pd
import pandas as pd
# Create the DatetimeIndex
# Here 'MS' represents month start frequency
didx = pd.date_range(pd.Timestamp("2000-01-15 08:00"),
periods = 5, freq ='MS')
# Print the DatetimeIndex
print(didx)

# snap the timestamp to the nearest frequency
didx.snap('Q')
