在nc数据处理时,以ERA5的小时数据为例,使用的时间为UTC,不同时区存在时间上的差异,如何将其转化为北京当地的时间呢?
https://confluence.ecmwf.int/display/CKB/ERA5%3A+data+documentation
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 7 20:53:05 2023
@author: xpji
"""
import xarray as xr
import numpy as np
import pandas as pd
from datetime import datetime
from dateutil import tz
def convert_time_zone(input_path, output_path, start_time, end_time):
# 设置时区
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('Asia/Shanghai')
# 打开NetCDF文件
pre = xr.open_dataset(input_path)
# 获取时间变量
time_str = pd.date_range(start=start_time, end=end_time, freq='1H').strftime('%Y-%m-%d %H:%M:%S')
result = []
for t in time_str:
dt = datetime.strptime(t, '%Y-%m-%d %H:%M:%S').replace(tzinfo=from_zone)
dt = dt.astimezone(to_zone)
print('原始时间:', t, '北京时间:', dt)
result.append(dt)
result_formatted = []
for dt in result:
dt_beijing = dt.strftime('%Y-%m-%d %H:%M:%S')
result_formatted.append(dt_beijing)
# 将result_formatted转换为与pre数据集的维度相同的DataArray
time_beijing = xr.DataArray(result_formatted, dims='time')
# 创建新的数据集
pre_beijing = pre.copy(deep=True)
pre_beijing['time'] = time_beijing
# 保存为新的NetCDF文件
pre_beijing.to_netcdf(output_path)
print("数据已保存为:", output_path)
convert_time_zone('./wind_850hpa_hourly.nc',
'./wind_850hpa_hourly_beijing.nc',
'2004-06-15 00:00:00', '2004-06-30 18:00:00')