Temperature and humidity, along with concentrations of ammonia and hydrogen sulfide, are critical environmental factors that significantly influence the growth and health of pigs within porcine habitats. The ability to accurately predict these environmental variables in pig houses is pivotal, as it provides crucial decision-making support for the precise and targeted regulation of the internal environmental conditions. This approach ensures an optimal living environment, essential for the well-being and healthy development of the pigs. The existing methodologies for forecasting environmental factors in pig houses are currently hampered by issues of low predictive accuracy and significant fluctuations in environmental conditions. To address these challenges in this study, a hybrid model incorporating the improved dung beetle algorithm (DBO), temporal convolutional networks (TCNs), and gated recurrent units (GRUs) is proposed for the prediction and optimization of environmental factors in pig barns. The model enhances the global search capability of DBO by introducing the Osprey Eagle optimization algorithm (OOA). The hybrid model uses the optimization capability of DBO to initially fit the time-series data of environmental factors, and subsequently combines the long-term dependence capture capability of TCNs and the non-linear sequence processing capability of GRUs to accurately predict the residuals of the DBO fit. In the prediction of ammonia concentration, the OTDBO–TCN–GRU model shows excellent performance with mean absolute error (MAE), mean square error (MSE), and coefficient of determination (R2) of 0.0474, 0.0039, and 0.9871, respectively. Compared with the DBO–TCN–GRU model, OTDBO–TCN–GRU achieves significant reductions of 37.2% and 66.7% in MAE and MSE, respectively, while the R2 value is improved by 2.5%. Compared with the OOA model, the OTDBO–TCN–GRU achieved 48.7% and 74.2% reductions in the MAE and MSE metrics, respectively, while the R2 value improved by 3.6%. In addition, the improved OTDBO–TCN–GRU model has a prediction error of less than 0.3 mg/m3 for environmental gases compared with other algorithms, and has less influence on sudden environmental changes, which shows the robustness and adaptability of the model for environmental prediction. Therefore, the OTDBO–TCN–GRU model, as proposed in this study, optimizes the predictive performance of environmental factor time series and offers substantial decision support for environmental control in pig houses.