Skip to content

dimensions

Functions to create and manipulate dimensions for netCDF files.

as_naive_timestamp

as_naive_timestamp(
    d: Union[datetime, Timestamp]
) -> Timestamp

Convert a date-time object to a naive timestamp.

Source code in src/efts_io/dimensions.py
77
78
79
80
81
82
83
84
85
86
def as_naive_timestamp(d: Union[datetime, pd.Timestamp]) -> pd.Timestamp:
    """Convert a date-time object to a naive timestamp."""
    return pd.Timestamp(
        year=d.year,
        month=d.month,
        day=d.day,
        hour=d.hour,
        minute=d.minute,
        second=d.second,
    )

cftimes_to_pdtstamps

cftimes_to_pdtstamps(
    cftimes: Iterable[DatetimeGregorian],
    tz_str: Optional[str] = None,
) -> ndarray[Timestamp, Timestamp]

Convert one or more Climate and Forecast (CF) times to timestamps.

Source code in src/efts_io/dimensions.py
302
303
304
305
306
307
def cftimes_to_pdtstamps(
    cftimes: Iterable[DatetimeGregorian],
    tz_str: Optional[str] = None,
) -> np.ndarray[pd.Timestamp,pd.Timestamp]:
    """Convert one or more Climate and Forecast (CF) times to timestamps."""
    return _as_tstamps(cftimes, tz_str)

check_is_utc

check_is_utc(d: Any) -> bool

Check that a date-time is in the UTC time zone.

Source code in src/efts_io/dimensions.py
39
40
41
42
43
44
45
46
47
def check_is_utc(d: Any) -> bool:
    """Check that a date-time is in the UTC time zone."""
    a = pd.Timestamp(d)
    if a.tz is None:
        return True  # ?
    z = a.tz
    from datetime import timezone

    return z == timezone.utc

create_netcdf_time_axis

create_netcdf_time_axis(
    d: Any,
    time_step: str = "hours since",
    tzoffset: Optional[str] = None,
) -> str

Create a time axis unit known to work for netCDF.

Source code in src/efts_io/dimensions.py
68
69
70
71
72
73
74
def create_netcdf_time_axis(d: Any, time_step: str = "hours since", tzoffset: Optional[str] = None) -> str:
    """Create a time axis unit known to work for netCDF."""
    if tzoffset is None:
        if not check_is_utc(d):
            raise ValueError("date time must have UTC or GMT as time zone")
        tzoffset = "+0000"
    return " ".join([time_step, iso_date_time_str(as_naive_timestamp(d)), tzoffset])

create_time_info

create_time_info(
    start: Any,
    n: int,
    time_step: str = "hours since",
    time_step_delta: int = 1,
    tzoffset: Optional[str] = None,
) -> Dict[str, Any]

Helper function to create the definition of the time dimension for use in a netCDF file.

Source code in src/efts_io/dimensions.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def create_time_info(
    start: Any,
    n: int,
    time_step: str = "hours since",
    time_step_delta: int = 1,
    tzoffset: Optional[str] = None,
) -> Dict[str, Any]:
    """Helper function to create the definition of the time dimension for use in a netCDF file."""
    return {
        UNITS_ATTR_KEY: create_netcdf_time_axis(
            d=start,
            time_step=time_step,
            tzoffset=tzoffset,
        ),
        "values": np.arange(0, n) * time_step_delta,
    }

create_timestamps

create_timestamps(
    time_dim_info: Dict[str, Any],
    tz_str: Optional[str] = None,
) -> ndarray[Timestamp, Timestamp]

Create time axis timestamps given the time dimension information.

Source code in src/efts_io/dimensions.py
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
def create_timestamps(
    time_dim_info: Dict[str, Any],
    tz_str: Optional[str] = None,
) -> np.ndarray[pd.Timestamp,pd.Timestamp]:
    """Create time axis timestamps given the time dimension information."""
    import xarray as xr

    axis_units = time_dim_info[UNITS_ATTR_KEY]
    axis_values = time_dim_info["values"]
    var = xr.Variable(
        dims=[TIME_DIMNAME],
        data=axis_values,
        encoding={FILLVALUE_ATTR_KEY: None},
        attrs={
            UNITS_ATTR_KEY: axis_units,
        },
    )
    from xarray.coding import times

    decod = times.CFDatetimeCoder(use_cftime=True)
    time_coords = decod.decode(var, name=TIME_DIMNAME)
    return cftimes_to_pdtstamps(time_coords.values, tz_str=tz_str)

iso_date_time_str

iso_date_time_str(t: Any) -> str

Convert a date-time object to a string in ISO format, using space as separator.

Source code in src/efts_io/dimensions.py
22
23
24
def iso_date_time_str(t: Any) -> str:
    """Convert a date-time object to a string in ISO format, using space as separator."""
    return pd.Timestamp(t).isoformat(" ")