Thursday, September 4, 2025
HomeLanguagesPython | Pandas DatetimeIndex.snap()

Python | Pandas DatetimeIndex.snap()

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 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 : DatetimeIndex

Example #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)


Output :

Now we want to convert the given DatetimeIndex object timestamp values to the nearest frequency based on the input.




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


Output :

As we can see in the output, the function has snapped each timestamp value in the given DatetimeIndex object.
 
Example #2: 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 '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)


Output :

Now we want to convert the given DatetimeIndex object timestamp values to the nearest frequency based on the input.




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


Output :

As we can see in the output, the function has snapped each timestamp value in the given DatetimeIndex object.

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS