Skip to content

Instantly share code, notes, and snippets.

@Zeitsperre
Last active July 27, 2021 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zeitsperre/a6ad7c10fc5197ae7db647b4bcc7bf35 to your computer and use it in GitHub Desktop.
Save Zeitsperre/a6ad7c10fc5197ae7db647b4bcc7bf35 to your computer and use it in GitHub Desktop.
Calendar conversion using xclim/xarray
from pathlib import Path
from typing import List
import xarray as xr
from xclim.core import calendar as xcal
root_dir = Path(Path().cwd().root)
source_dir = root_dir.joinpath("my/source/files/folder/")
processed_files = [x for x in source_dir.glob("*.nc")]
def adjust_calendars(files: List[Path], sources: Path):
for file in files:
ds = xr.open_dataset(file)
try:
calendar = ds.time.calendar
except AttributeError:
calendar = xcal.get_calendar(ds, dim="time")
if calendar != "default":
dsOut = xcal.convert_calendar(ds, "default", dim="time") # noqa
else:
ds.close()
continue
dsOut.to_netcdf(sources.joinpath(f"{file.stem}_calendar-fixed.nc"))
dsOut.close()
ds.close()
if __name__ == "__main__":
adjust_calendars(processed_files, source_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment