Groundwater resources play a vital role in production, human life and economic development. Effective prediction of groundwater levels would support better water resources management. Although machine learning algorithms have been studied and applied in many domains with good enough results, the researches in hydrologic domains are not adequate. This paper proposes a novel deep learning algorithm for groundwater level prediction based on spatiotemporal attention mechanism. Short-term (one month ahead) and long-term (twelve months ahead) prediction of groundwater level are conducted with observed groundwater levels collected from several boreholes in the middle reaches of the Heihe River Basin in northwestern China. Mean Absolute Error (MAE) and Root Mean Square Error (RMSE) are used to evaluate the performance of the proposed algorithm and several baseline models (i.e., SVR, Support Vector Regression; FNN, Feedforward Neural Networks; LSTM, Long Short-Term Memory neural network). The results show that the proposed model can effectively improve the prediction accuracy compared to the baseline models with MAE of 0.0754, RMSE of 0.0952 for short-term prediction and MAE of 0.0983, RMSE of 0.1215 for long-term prediction. This study provides a feasible and accurate approach for groundwater prediction which may facilitate decision making for water management.