- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Pandas - Snap time stamps in DateTimeIndex to nearest occurring frequency\n\n
To snap time stamps in DateTimeIndex to nearest occurring frequency, use the DateTimeIndex.snap() method. Set the frequency using the freq parameter.
At first, import the required libraries −
import pandas as pd
Create a DatetimeIndex with period 6 and frequency as D i.e. day −
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Adelaide', freq='D')
Display DateTimeIndex −
print("DateTimeIndex...\n", datetimeindex)
Snap time stamps to nearest occurring i.e. Month end here −
print("\nSnap time stamps to nearest occurring frequency...\n", datetimeindex.snap(freq='M'))
Example
Following is the code −
import pandas as pd # DatetimeIndex with period 6 and frequency as D i.e. day # The timezone is Australia/Adelaide datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Adelaide', freq='D') # display DateTimeIndex print("DateTimeIndex...\n", datetimeindex) # display DateTimeIndex frequency print("\nDateTimeIndex frequency...\n", datetimeindex.freq) # Snap time stamps to nearest occurring i.e. Month end here print("\nSnap time stamps to nearest occurring frequency...\n", datetimeindex.snap(freq='M'))
Output
This will produce the following code −
DateTimeIndex... DatetimeIndex(['2021-10-20 02:30:50+10:30', '2021-10-21 02:30:50+10:30', '2021-10-22 02:30:50+10:30', '2021-10-23 02:30:50+10:30', '2021-10-24 02:30:50+10:30', '2021-10-25 02:30:50+10:30'], dtype='datetime64[ns, Australia/Adelaide]', freq='D') DateTimeIndex frequency... <Day> Snap time stamps to nearest occurring frequency... DatetimeIndex(['2021-10-31 02:30:50+10:30', '2021-10-31 02:30:50+10:30', '2021-10-31 02:30:50+10:30', '2021-10-31 02:30:50+10:30', '2021-10-31 02:30:50+10:30', '2021-10-31 02:30:50+10:30'], dtype='datetime64[ns, Australia/Adelaide]', freq=None)
Advertisements