Pandas DatetimeIndex function snap() in Python
The Pandas DatetimeIndex function snap() used to retrieve snap time stamps to nearest occurring frequency. It returns DatetimeIndex that includes nearest occurring frequency.
Syntax
 1 DatetimeIndex.snap(freq = 'S')
freq : It specifies the frequency to snap. If not specified, the default value will be 'S'(second).
snap() function
 1 import pandas as pd
 2 
 3 dIndex = pd.date_range('2022-01-15 9:15:00',freq ='Q',
 4                           periods = 3, tz = 'Asia/Calcutta')
 5 
 6 print('The DatetimeIndex object :')
 7 print(dIndex)
 8 
 9 res = dIndex.snap(freq = 'MS')
 10 print('The snap with specified frequency :')
 11 print(res)
In the above example, a DatetimeIndex object is created by using date_range() by passing a date, frequency and periods. A snap() function is called by passing a frequency that returns DatetimeIndex snapped each timestamp value in the given DatetimeIndex object. The result is assign to the variable that will be printed on console.
Output
 1 The DatetimeIndex object :
 2 DatetimeIndex(['2022-03-31 09:15:00+05:30', '2022-06-30 09:15:00+05:30',
 3                '2022-09-30 09:15:00+05:30'],
 4               dtype='datetime64[ns, Asia/Calcutta]', freq='Q-DEC')
 5 
 6 The snap with specified frequency :
 7 DatetimeIndex(['2022-04-01 09:15:00+05:30', '2022-07-01 09:15:00+05:30',
 8                '2022-10-01 09:15:00+05:30'],
 9               dtype='datetime64[ns, Asia/Calcutta]', freq=None)

Example 2

Example 2
 1 import pandas as pd
 2 
 3 dIndex = pd.date_range('2022-01-01 12:30:32',
 4 	periods = 3, freq = 'QS')
 5 
 6 print('The DatetimeIndex object :')
 7 print(dIndex)
 8 
 9 res = dIndex.snap(freq = 'MS')
 10 print('The snap with specified frequency :')
 11 print(res)
In the above example, a DatetimeIndex object is created by using date_range() by passing a date, frequency and periods. A snap() function is called by passing a frequency that returns DatetimeIndex snapped each timestamp value in the given DatetimeIndex object. The result is assign to the variable that will be print.
Output
 1 The DatetimeIndex object :
 2 DatetimeIndex(['2022-01-01 12:30:32', '2022-04-01 12:30:32',
 3                '2022-07-01 12:30:32'],
 4               dtype='datetime64[ns]', freq='QS-JAN')
 5 
 6 The snap with specified frequency :
 7 DatetimeIndex(['2022-01-01 12:30:32', '2022-04-01 12:30:32',
 8                '2022-07-01 12:30:32'],
 9               dtype='datetime64[ns]', freq=None)
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us