Last active
July 27, 2021 15:46
-
-
Save Zeitsperre/a6ad7c10fc5197ae7db647b4bcc7bf35 to your computer and use it in GitHub Desktop.
Calendar conversion using xclim/xarray
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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