How to utilize time series in Pandas?
Last Updated :
03 Mar, 2021
The pandas library in python provides a standard set of time series tools and data algorithms. By this, we can efficiently work with very large time series and easily slice and dice, aggregate, and resample irregular and fixed frequency time series.
Time series data is an important form of structured data which is used in finance, economics, ecology, etc. Anything that is observed or measured at many points in time forms a time series.
- Timestamps: These are the specific instants in time
- Fixed period: This will represent such as the month of May 25 or the full year 1999.
Modules in DateTime
- date: This module is used to store the calendar in the format of year, month, date.
- time: This module is used to get and display the time in the format of hours, minutes, seconds, and microseconds.
- datetime: This module is used to store both date and time.
- timedelta: This module is used to get the difference between two datetime values.
Below are various examples that depict how to utilize time series in the pandas library:
Example 1: Display the current date and time. In this program, we are going to display current date and time.
Python3
from datetime import datetime
datetime.now()
|
Output:

Example 2: Program to display hour, minutes, seconds, month, year, day individually from the module.
Python3
from datetime import datetime
a = datetime.now()
print (a.year)
print (a.day)
print (a.month)
print (a.hour)
print (a.minute)
print (a.second)
print (a.microsecond)
print (a.date)
|
Output:

Example 3: Difference between two dates. We can get hours, days and minute difference using timedelta module.
Python3
from datetime import timedelta
deltaresult = datetime( 2027 , 5 , 7 ) - datetime( 2021 , 6 , 24 )
print (deltaresult)
print (deltaresult.days)
print (deltaresult.seconds)
|
Output:

If we want to generate time series data python will support date_range module. This will generate dates within the given frequency. It is available in the pandas module.
Syntax: pandas.date_range(start=None, end=None, periods=None, freq=None)
Parameters:
- start: start date time from start date.
- end: specify end date time.
- freq: represents a frequency like hours or minutes or seconds.
Example 4: In this program, we can start with 2021 January 1st and display the dates up to march using the date_range method.
Python3
import pandas as pd
dates = pd.date_range( '1/1/2021' , periods = 75 )
print (dates)
|
Output:

Generating values to corresponding dates by using timeseries as indices.
Example 5: In this program, we are giving values to dates by setting dates as indexes to each value.
Python3
import pandas as pd
import numpy as np
dates = pd.date_range( '1/1/2021' , periods = 75 )
results = pd.Series(np.arange( 75 ), index = dates)
print (results)
print (pd.DataFrame(results))
|
Output:

We can convert data string columns to datetime type by using the below method.
Syntax:
pandas.to_datetime(column_name)
Example 6: In this program, we will convert string data into datetime type.
Python3
import pandas as pd
data = pd.DataFrame({ 'dates' : [ '1/2/2021' ,
'2/4/2020' ,
'1/3/2021' ,
'4/12/2017' ],
'customers' : [ 100 , 30 , 56 , 56 ]})
data
data[ 'dates' ] = pd.to_datetime(data[ 'dates' ])
data
|
Output:


Example 7: In this program, we are going to take some time series data as an index, convert it and verify whether they are equal or not.
Python3
import pandas as pd
data = pd.DataFrame({ 'dates' : [ '1/2/2021' , '2/4/2020' ,
'1/3/2021' , '4/12/2017' ,
'1/2/2021' , '2/4/2020' ,
'1/3/2021' ],
'customers' : [ 100 , 30 , 56 ,
56 , 23 , 45 , 67 ]})
data
data[ 'dates' ] = pd.to_datetime(data[ 'dates' ])
data
print (data[ 'dates' ].nunique())
data[ 'dates' ].value_counts()
|
Output:



Example 8: Program to display a histogram from a data frame having DateTime objects.
Python3
import pandas as pd
data = pd.DataFrame({ 'dates' : [ '1/2/2021' , '2/4/2020' ,
'1/3/2021' , '4/12/2017' ,
'1/2/2021' , '2/4/2020' ,
'1/3/2021' ],
'customers' : [ 100 , 30 , 56 ,
56 , 23 , 45 , 67 ]})
data
data[ 'dates' ] = pd.to_datetime(data[ 'dates' ])
data[ 'dates' ].hist(figsize = ( 10 , 5 ), color = "green" )
|
Output:

Similar Reads
How to utilise timeseries in pandas?
An ordered stream of values for a variable at evenly spaced time periods is known as a time series. Timeseries are useful in identifying the underlying factors and structures that resulted in the observed data and After you've fitted a model, one can move on to forecasting, monitoring. some applicat
3 min read
How to Merge âNot Matchingâ Time Series with Pandas ?
In this article, we are going to see how to merge âNot Matchingâ Time Series with Pandas. Time series is a sequence of observations recorded at regular time intervals. Time series analysis can be useful to see how a given asset, security, or economic variable changes over time Usually, data consists
3 min read
How to Plot a Vertical Line on a Time Series Plot in Pandas
When working with time series data in Pandas, it is often necessary to highlight specific points or events in the data. One effective way to do this is by plotting vertical lines on the time series plot. In this article, we will explore how to plot a vertical line on a time series plot in Pandas, co
3 min read
What is a trend in time series?
Time series data is a sequence of data points that measure some variable over ordered period of time. It is the fastest-growing category of databases as it is widely used in a variety of industries to understand and forecast data patterns. So while preparing this time series data for modeling it's i
3 min read
How to Resample Time Series Data in Python?
In time series, data consistency is of prime importance, resampling ensures that the data is distributed with a consistent frequency. Resampling can also provide a different perception of looking at the data, in other words, it can add additional insights about the data based on the resampling frequ
5 min read
Basic of Time Series Manipulation Using Pandas
Although the time series is also available in the Scikit-learn library, data science professionals use the Pandas library as it has compiled more features to work on the DateTime series. We can include the date and time for every record and can fetch the records of DataFrame. We can find out the da
4 min read
How to Plot a Time Series in Matplotlib?
Time series data is the data marked by some time. Each point on the graph represents a measurement of both time and quantity. A time-series chart is also known as a fever chart when the data are connected in chronological order by a straight line that forms a succession of peaks and troughs. x-axis
4 min read
Python | Pandas Series.between_time()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.between_time() function selec
3 min read
Python | Pandas PeriodIndex.end_time
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 PeriodIndex.end_time attribute returns an Index object. The Index contains the
2 min read
Pandas Series dt.time | Extract Time from Time Stamp in Series
The Series.dt.time attribute returns a NumPy array containing time values of the timestamps in a Pandas series. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'D
2 min read