Time Series Forecasting using Pytorch

Last Updated : 03 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Time series forecasting plays a major role in data analysis, with applications ranging from anticipating stock market trends to forecasting weather patterns. In this article, we’ll dive into the field of time series forecasting using PyTorch and LSTM (Long Short-Term Memory) neural networks. We’ll uncover the critical preprocessing procedures that underpin the accuracy of our forecasts along the way.

Time Series Forecasting

Time series data is essentially a set of observations taken at regular periods of time. Time series forecasting attempts to estimate future values based on patterns and trends detected in historical data. Moving averages and traditional approaches like ARIMA have trouble capturing long-term dependencies in the data. LSTM is a type of recurrent neural network, that excels at capturing dependencies through time and able to intricate patterns.

Implementation of Time Series Forecasting

Prerequisites

Datasets

Here, we have used Yahoo Finance to get the share market dataset.

To install the Yahoo Finance, we can use the following command

!pip install yfinance

Step 1: Import Libraries and Set Configuration

This step involves importing various libraries essential for data processing, visualization, machine learning, and deep learning tasks.

Python
import seaborn as sns
from pylab import rcParams
import matplotlib.pyplot as plt
from matplotlib import rc

import pandas as pd
import numpy as np
from tqdm.notebook import tqdm

from sklearn.preprocessing import MinMaxScaler

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
from sklearn.metrics import mean_squared_error, r2_score
from collections import defaultdict

%matplotlib inline

sns.set(style='whitegrid', palette='muted', font_scale=1.2)

Colour_Palette = ['#01BEFE', '#FF7D00', '#FFDD00', '#FF006D', '#ADFF02', '#8F00FF']
sns.set_palette(sns.color_palette(Colour_Palette))

tqdm.pandas()

Step 2: Load and Inspect Data

Download the historical stock price data for Apple Inc. (AAPL) from Yahoo Finance. Inspect the data using df.head() and df.info() to understand its structure and contents.

Python
import yfinance as yf
from datetime import date

end_date = date.today().strftime("%Y-%m-%d")
start_date = '1990-01-01'

df = yf.download('AAPL', start=start_date, end=end_date)

# Inspect the data
print(df.head())
print(df.info())

Output:

[*********************100%%**********************]  1 of 1 completed                Open      High       Low     Close  Adj Close     Volume
Date
1990-01-02 0.314732 0.334821 0.312500 0.332589 0.262418 183198400
1990-01-03 0.339286 0.339286 0.334821 0.334821 0.264179 207995200
1990-01-04 0.341518 0.345982 0.332589 0.335938 0.265060 221513600
1990-01-05 0.337054 0.341518 0.330357 0.337054 0.265941 123312000
1990-01-08 0.334821 0.339286 0.330357 0.339286 0.267702 101572800
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 8726 entries, 1990-01-02 to 2024-08-21
Data columns (total 6 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Open 8726 non-null float64
1 High 8726 non-null float64
2 Low 8726 non-null float64
3 Close 8726 non-null float64
4 Adj Close 8726 non-null float64
5 Volume 8726 non-null int64
dtypes: float64(5), int64(1)
memory usage: 477.2 KB
None

Step 3: Plot Data

Define a function to plot the data using line plots for each column in the DataFrame. This helps visualize trends and patterns in the data.

Python
import matplotlib.dates as mdates

def data_plot(df):
    # Plot line charts
    df_plot = df.copy()

    ncols = 2
    nrows = int(round(df_plot.shape[1] / ncols, 0))

    fig, ax = plt.subplots(nrows=nrows, ncols=ncols, sharex=True, figsize=(14, 7))
    for i, ax in enumerate(fig.axes):
        sns.lineplot(data=df_plot.iloc[:, i], ax=ax)
        ax.tick_params(axis="x", rotation=30, labelsize=10, length=0)
        ax.xaxis.set_major_locator(mdates.AutoDateLocator())
    fig.tight_layout()
    plt.show()

# Plot the data
data_plot(df)

Output:

download

Step 4: Preprocess Data

In this step, we split the data into training and testing sets, and normalize the values using MinMaxScaler. This preprocessing is essential for preparing the data for machine learning models.

  • math.ceil: Used to calculate the number of training data points (80% of the total data).
  • train_data and test_data: Split the DataFrame into training and testing sets.
  • MinMaxScaler: Scales the data to a range of [0, 1]. This normalization helps the neural network to converge faster.
Python
import math
from sklearn.preprocessing import MinMaxScaler

# Train test split
training_data_len = math.ceil(len(df) * .8)
print(training_data_len)

# Splitting the dataset
train_data = df[:training_data_len].iloc[:, :1]
test_data = df[training_data_len:].iloc[:, :1]
print(train_data.shape, test_data.shape)

# Selecting Open Price values
dataset_train = train_data.Open.values
# Reshaping 1D to 2D array
dataset_train = np.reshape(dataset_train, (-1, 1))
print(dataset_train.shape)

# Selecting Open Price values
dataset_test = test_data.Open.values
# Reshaping 1D to 2D array
dataset_test = np.reshape(dataset_test, (-1, 1))
print(dataset_test.shape)

scaler = MinMaxScaler(feature_range=(0, 1))
# Scaling dataset
scaled_train = scaler.fit_transform(dataset_train)
print(scaled_train[:5])

# Normalizing values between 0 and 1
scaled_test = scaler.fit_transform(dataset_test)
print(scaled_test[:5])

Output:

6981
(6981, 1) (1745, 1)
(6981, 1)
(1745, 1)
[[0.00486252]
[0.00546016]
[0.00551449]
[0.00540584]
[0.00535148]]
[[0.01871712]
[0.01806869]
[0.02011373]
[0.01936554]
[0.01735791]]

Step 5: Create Sequences and Labels for Training and Testing

We structure the data into sequences for the LSTM model. Each sequence contains a specified number of time steps. We then convert the data into PyTorch tensors, which are necessary for input into the PyTorch model.

  • sequence_length: The number of time steps the model looks back to make a prediction.
  • X_train and y_train: Arrays to hold the input sequences and their corresponding labels for training.
  • X_test and y_test: Arrays for testing data.
  • torch.tensor: Converts the numpy arrays into PyTorch tensors.
Python
# Create sequences and labels for training data
sequence_length = 50  # Number of time steps to look back
X_train, y_train = [], []
for i in range(len(scaled_train) - sequence_length):
    X_train.append(scaled_train[i:i + sequence_length])
    y_train.append(scaled_train[i + sequence_length])  # Predicting the value right after the sequence
X_train, y_train = np.array(X_train), np.array(y_train)

# Convert data to PyTorch tensors
X_train = torch.tensor(X_train, dtype=torch.float32)
y_train = torch.tensor(y_train, dtype=torch.float32)
print(X_train.shape, y_train.shape)

# Create sequences and labels for testing data
sequence_length = 30  # Number of time steps to look back
X_test, y_test = [], []
for i in range(len(scaled_test) - sequence_length):
    X_test.append(scaled_test[i:i + sequence_length])
    y_test.append(scaled_test[i + sequence_length])  # Predicting the value right after the sequence
X_test, y_test = np.array(X_test), np.array(y_test)

# Convert data to PyTorch tensors
X_test = torch.tensor(X_test, dtype=torch.float32)
y_test = torch.tensor(y_test, dtype=torch.float32)
print(X_test.shape, y_test.shape)

Output:

torch.Size([6931, 50, 1]) torch.Size([6931, 1])
torch.Size([1715, 30, 1]) torch.Size([1715, 1])

Step 6: Define and Train the LSTM Model

Define an LSTM model for time series forecasting. The model includes an LSTM layer followed by a fully connected layer. Train the model using the training data and evaluate it on the test data.

  • LSTMModel: A PyTorch neural network class with an LSTM layer and a linear layer.
  • Device Configuration: Check if a GPU is available and use it if possible.
  • Hyperparameters: Settings like input size, hidden size, number of layers, dropout rate, batch size, learning rate, and number of epochs.
  • DataLoader: Utility to handle batching and shuffling of the dataset.
  • Training Loop: Loop over the dataset for a specified number of epochs, performing forward and backward passes and updating model weights.
Python
class LSTMModel(nn.Module):
    def __init__(self, input_size, hidden_size, num_layers, dropout=0.2):
        super(LSTMModel, self).__init__()
        self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True, dropout=dropout)
        self.linear = nn.Linear(hidden_size, 1)

    def forward(self, x):
        out, _ = self.lstm(x)
        out = self.linear(out[:, -1, :])
        return out

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(device)

input_size = 1
num_layers = 3  # Increased number of layers
hidden_size = 128  # Increased number of hidden units
output_size = 1
dropout = 0.2  # Added dropout for regularization

model = LSTMModel(input_size, hidden_size, num_layers, dropout).to(device)
loss_fn = nn.MSELoss(reduction='mean')
optimizer = optim.Adam(model.parameters(), lr=1e-3)  # Learning rate

batch_size = 32  # Adjusted batch size
train_dataset = TensorDataset(X_train, y_train)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_dataset = TensorDataset(X_test, y_test)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)

num_epochs = 100  # Increased number of epochs
train_hist = []
test_hist = []

for epoch in range(num_epochs):
    total_loss = 0.0
    model.train()
    for batch_X, batch_y in train_loader:
        batch_X, batch_y = batch_X.to(device), batch_y.to(device)
        predictions = model(batch_X)
        loss = loss_fn(predictions, batch_y)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        total_loss += loss.item()

    average_loss = total_loss / len(train_loader)
    train_hist.append(average_loss)

    model.eval()
    with torch.no_grad():
        total_test_loss = 0.0

        for batch_X_test, batch_y_test in test_loader:
            batch_X_test, batch_y_test = batch_X_test.to(device), batch_y_test.to(device)
            predictions_test = model(batch_X_test)
            test_loss = loss_fn(predictions_test, batch_y_test)

            total_test_loss += test_loss.item()

        average_test_loss = total_test_loss / len(test_loader)
        test_hist.append(average_test_loss)

    if (epoch + 1) % 10 == 0:
        print(f'Epoch [{epoch + 1}/{num_epochs}] - Training Loss: {average_loss:.4f}, Test Loss: {average_test_loss:.4f}')

Output:

cuda
Epoch [10/100] - Training Loss: 0.0003, Test Loss: 0.0005
Epoch [20/100] - Training Loss: 0.0001, Test Loss: 0.0003
Epoch [30/100] - Training Loss: 0.0002, Test Loss: 0.0003
Epoch [40/100] - Training Loss: 0.0001, Test Loss: 0.0003
Epoch [50/100] - Training Loss: 0.0001, Test Loss: 0.0003
Epoch [60/100] - Training Loss: 0.0001, Test Loss: 0.0003
Epoch [70/100] - Training Loss: 0.0001, Test Loss: 0.0003
Epoch [80/100] - Training Loss: 0.0001, Test Loss: 0.0002
Epoch [90/100] - Training Loss: 0.0001, Test Loss: 0.0002
Epoch [100/100] - Training Loss: 0.0001, Test Loss: 0.0002
Python
x = np.linspace(1,num_epochs,num_epochs)
plt.plot(x,train_hist,scalex=True, label="Training loss")
plt.plot(x, test_hist, label="Test loss")
plt.legend()
plt.show()

Output:

download


Step 7: Forecast Future Values and Evaluate the Model

Use the trained model to forecast future values. Evaluate the model’s performance using metrics like RMSE and R² score.

  • Forecasting: Generate future values using the trained model.
  • Plotting: Visualize the actual and forecasted values.
  • Evaluation: Calculate RMSE and R² score to evaluate the model’s performance.
Python
num_forecast_steps = 30
sequence_to_plot = X_test.squeeze().cpu().numpy()
historical_data = sequence_to_plot[-1]

forecasted_values = []
with torch.no_grad():
    for _ in range(num_forecast_steps):
        historical_data_tensor = torch.as_tensor(historical_data).view(1, -1, 1).float().to(device)
        predicted_value = model(historical_data_tensor).cpu().numpy()[0, 0]
        forecasted_values.append(predicted_value)
        historical_data = np.roll(historical_data, shift=-1)
        historical_data[-1] = predicted_value

last_date = test_data.index[-1]
future_dates = pd.date_range(start=last_date + pd.DateOffset(1), periods=30)

plt.rcParams['figure.figsize'] = [14, 4]
plt.plot(test_data.index[-100:], test_data.Open[-100:], label="test_data", color="b")
plt.plot(test_data.index[-30:], test_data.Open[-30:], label='actual values', color='green')
plt.plot(test_data.index[-1:].append(future_dates), np.concatenate([test_data.Open[-1:], scaler.inverse_transform(np.array(forecasted_values).reshape(-1, 1)).flatten()]), label='forecasted values', color='red')

plt.xlabel('Time Step')
plt.ylabel('Value')
plt.legend()
plt.title('Time Series Forecasting')
plt.grid(True)
plt.show()

# Evaluate the model and calculate RMSE and R² score
model.eval()
with torch.no_grad():
    test_predictions = []
    for batch_X_test in X_test:
        batch_X_test = batch_X_test.to(device).unsqueeze(0)  # Add batch dimension
        test_predictions.append(model(batch_X_test).cpu().numpy().flatten()[0])

test_predictions = np.array(test_predictions)

# Calculate RMSE and R² score
rmse = np.sqrt(mean_squared_error(y_test.cpu().numpy(), test_predictions))
r2 = r2_score(y_test.cpu().numpy(), test_predictions)

print(f'RMSE: {rmse:.4f}')
print(f'R² Score: {r2:.4f}')

Output:

RMSE: 0.0173
R² Score: 0.9961
Plot

By plotting the test data, actual values and model’s forecasting data. We got a clear idea of how well the forecasted values are aligning with the actual time series.

The intriguing field of time series forecasting using PyTorch and LSTM neural networks has been thoroughly examined in this paper. In order to collect historical stock market data using Yahoo Finance module, we imported the yfinance library and started the preprocessing step. Then we applied crucial actions like data loading, train-test splitting, and data scaling to make sure our model could accurately learn from the data and make predictions.

For more accurate forecasts, additional adjustments, hyperparameter tuning, and optimization are frequently needed. To improve predicting capabilities, ensemble methods and other cutting-edge methodologies can be investigated.

We have barely begun to explore the enormous field of time series forecasting in this essay. There is a ton more to learn, from managing multi-variate time series to resolving practical problems in novel ways. With this knowledge in hand, you’re prepared to use PyTorch and LSTM neural networks to go out on your own time series forecasting adventures.

Enjoy your forecasting!

Get the Complete Notebook:

Notebook: click here.



Next Article

Similar Reads

Random Forest for Time Series Forecasting using R
Random Forest is an ensemble machine learning method that can be used for time series forecasting. It is based on decision trees and combines multiple decision trees to make more accurate predictions. Here's a complete explanation along with an example of using Random Forest for time series forecasting in R. Time Series ForecastingTime series forec
7 min read
Time Series and Forecasting Using R
Time series forecasting is the process of using historical data to make predictions about future events. It is commonly used in fields such as finance, economics, and weather forecasting. R is a powerful programming language and software environment for statistical computing and graphics that is widely used for time series forecasting. What is Time
9 min read
TIme Series Forecasting using TensorFlow
TensorFlow emerges as a powerful tool for data scientists performing time series analysis through its ability to leverage deep learning techniques. By incorporating deep learning into time series analysis, we can achieve significant advancements in both the depth and accuracy of our forecasts. TensorFlow sits at the forefront of this transformative
8 min read
Time Series Forecasting for Predicting Store Sales Using Prophet
Time series forecasting is a crucial aspect of business analytics, enabling companies to predict future trends based on historical data. Accurate forecasting can significantly impact decision-making processes, inventory management, and overall business strategy. One of the powerful tools for time series forecasting is Prophet, an open-source librar
10 min read
Time Series Forecasting Using TensorFlow in R
Time series forecasting involves using past data collected at regular intervals to predict future values of a variable that changes over time. By analyzing historical data, we can understand trends, seasonal patterns, and cyclical behaviors, which helps in making more informed decisions. Applications and Use CasesTime series forecasting to plan bet
11 min read
Time Series Forecasting using Recurrent Neural Networks (RNN) in TensorFlow
Time Series Data: Each data point in a time series is linked to a timestamp, which shows the exact time when the data was observed or recorded. Many fields, including finance, economics, weather forecasting, and machine learning, frequently employ this kind of data. The fact that time series data frequently display patterns or trends across time, s
13 min read
Python | ARIMA Model for Time Series Forecasting
A Time Series is defined as a series of data points indexed in time order. The time order can be daily, monthly, or even yearly. Given below is an example of a Time Series that illustrates the number of passengers of an airline per month from the year 1949 to 1960. Time Series Forecasting Time Series forecasting is the process of using a statistica
5 min read
Univariate Time Series Analysis and Forecasting
Time series data is one of the most challenging tasks in machine learning as well as the real-world problems related to data because the data entities not only depend on the physical factors but mostly on the chronological order in which they have occurred. We can forecast a target value in the time series based on a single feature that is univaria
15+ min read
Autoregressive (AR) Model for Time Series Forecasting
Autoregressive models, often abbreviated as AR models, are a fundamental concept in time series analysis and forecasting. They have widespread applications in various fields, including finance, economics, climate science, and more. In this comprehensive guide, we will explore autoregressive models, how they work, their types, and practical examples
11 min read
Multivariate Time Series Forecasting with GRUs
Multivariate forecasting steps up as a game-changer in business analysis, bringing a fresh perspective that goes beyond the limits of one-variable predictions. In this article, we will explore the world of multivariate forecasting, peeling back the layers to understand its core, explore its applications, and grasp the revolutionary influence it has
9 min read
Multivariate Time Series Forecasting with LSTMs in Keras
Multivariate forecasting entails utilizing multiple time-dependent variables to generate predictions. This forecasting approach incorporates historical data while accounting for the interdependencies among the variables within the model. In this article, we will explore the world of multivariate forecasting using LSTMs, peeling back the layers to u
8 min read
How to Remove Non-Stationarity in Time Series Forecasting
Removing non-stationarity in time series data is crucial for accurate forecasting because many time series forecasting models assume stationarity, where the statistical properties of the time series do not change over time. Non-stationarity can manifest as trends, seasonality, or other forms of irregular patterns in the data. The article comprehens
7 min read
Time Series Forecasting with Support Vector Regression
Time series forecasting is a critical aspect of data analysis, with applications spanning from financial markets to weather predictions. In recent years, Support Vector Regression (SVR) has emerged as a powerful tool for time series forecasting due to its ability to handle nonlinear relationships and high-dimensional data. In this project, we'll de
11 min read
Exponential Smoothing for Time Series Forecasting
Exponential smoothing is a popular time series forecasting method known for its simplicity and accuracy in predicting future trends based on historical data. It assumes that future patterns will be similar to recent past data and focuses on learning the average demand level over time. In this article, we will make a detailed analysis of the Exponen
11 min read
Time Series Forecasting as Supervised Learning
Time series forecasting involves predicting future values based on previously observed data points. By reframing it as a supervised learning problem, you can leverage a variety of machine learning algorithms, both linear and nonlinear, to improve the forecasting accuracy. In this article, we will see how we can consider a supervised learning model.
3 min read
Time Series Analysis and Forecasting
Time series analysis and forecasting are crucial for predicting future trends, behaviors, and behaviours based on historical data. It helps businesses make informed decisions, optimize resources, and mitigate risks by anticipating market demand, sales fluctuations, stock prices, and more. Additionally, it aids in planning, budgeting, and strategizi
15+ min read
Time Series Forecasting in R with Holt-Winters
Time series forecasting is an essential technique used in various fields such as finance, economics, weather prediction, and inventory management. The Holt-Winters method is a popular approach for forecasting time series data, particularly when dealing with seasonality. In this article, we will explore the theory behind the Holt-Winters method and
3 min read
What is Lag in Time Series Forecasting
Time series forecasting is a crucial aspect of predictive modeling, often used in fields like finance, economics, and meteorology. It involves using historical data points to predict future trends. One important concept within time series analysis is lag, which plays a significant role in understanding and modeling the relationship between past and
9 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', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime
2 min read
PyTorch vs PyTorch Lightning
The PyTorch research team at Facebook AI Research (FAIR) introduced PyTorch Lightning to address these challenges and provide a more organized and standardized approach. In this article, we will see the major differences between PyTorch Lightning and Pytorch. Table of Content PytorchPytorch Lightning: Advanced Framework of PytorchPytorch vs Pytorch
9 min read
How to disable GPU in PyTorch (force Pytorch to use CPU instead of GPU)?
PyTorch is a deep learning framework that offers GPU acceleration. This enables the users to utilize the GPU's processing power. The main goal is to accelerate the training and interference processes of deep learning models. PyTorch automatically utilizes the GPU for operations and this leads to quicker computation times. Using the GPU for PyTorch
5 min read
Netflix Stock Price Prediction & Forecasting using Machine Learning in R
Recently, many people have been paying attention to the stock market as it offers high risks and high returns. In simple words, "Stock" is the ownership of a small part of a company. The more stock you have the bigger the ownership is. Using machine learning algorithms to predict a company's stock price aims to forecast the future value of the comp
9 min read
Demand forecasting in retail using catboost
In the fast-paced world of retail, accurate demand forecasting is crucial for optimizing inventory management, minimizing costs, and ensuring customer satisfaction. Traditional forecasting methods often fall short in capturing the complexity and dynamic nature of retail demand. This is where advanced machine learning techniques like CatBoost come i
8 min read
Inventory Demand Forecasting using Machine Learning - Python
The vendors who are selling everyday items need to keep their stock up to date so, that no customer returns from their shop empty hand.  Inventory Demand Forecasting using Machine LearningIn this article, we will try to implement a machine learning model which can predict the stock amount for the different products which are sold in different store
6 min read
Share Price Forecasting Using Facebook Prophet
Time series forecast can be used in a wide variety of applications such as Budget Forecasting, Stock Market Analysis, etc. But as useful it is also challenging to forecast the correct projections, Thus can't be easily automated because of the underlying assumptions and factors. The analysts who produced accurate forecasts are also rare, and there i
6 min read
How to Plot Multiple Series/Lines in a Time Series Using Plotly in R?
Plotly is a powerful and flexible graphing library that enables the creation of interactive plots in R. It is especially useful for visualizing time series data with multiple lines or series. In this article, we will cover how to plot multiple time series in a single plot using Plotly in R. Multiple Time SeriesMultiple time series involve more than
5 min read
DeepAR Forecasting Algorithm
In the field of time series forecasting, where the ability to predict future values based on historical data is crucial, advanced machine learning algorithms have become indispensable. One such powerful algorithm is DeepAR, which has gained prominence for its effectiveness in handling complex temporal patterns and generating accurate forecasts. Dee
8 min read
Fuel Efficiency Forecasting with CatBoost
The automobile sector is continuously looking for new and creative ways to cut fuel use in its pursuit of economy, and sustainability. Comprehending car fuel usage has become more crucial due to the increase in gas costs and the increased emphasis on environmental sustainability. A technique for this would be to forecast and examine fuel use using
7 min read
Pandas Series dt.freq | Retrieve Frequency of Pandas Time Series
Pandas dt.freq attribute returns the time series frequency applied on the given series object if any, else it returns None. Examples C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_da
2 min read
Pandas Series dt.normalize() | Normalize Time in Pandas Series
The dt.normalize() method converts times to midnight. The time component of the date-time is converted to midnight i.e. 00:00:00. This is useful in cases when the time does not matter. Length is unaltered. The time zones are unaffected. Example: C/C++ Code import pandas as pd sr = pd.Series(pd.date_range('2012-12-31 09:45', periods = 5, freq = 'M',
2 min read