The Unit Class

The primary functionality of cf_units is supplied by the Unit class:

class cf_units.Unit(unit, calendar=None)[source]

A class to represent S.I. units and support common operations to manipulate such units in a consistent manner as per UDUNITS-2.

These operations include scaling the unit, offsetting the unit by a constant or time, inverting the unit, raising the unit by a power, taking a root of the unit, taking a log of the unit, multiplying the unit by a constant or another unit, dividing the unit by a constant or another unit, comparing units, copying units and converting unit data to single precision or double precision floating point numbers.

This class also supports time and calendar defintion and manipulation.

calendar = None

Represents the unit calendar name, see cf_units.CALENDARS

category = None

Is this an unknown unit, a no-unit, or a UDUNITS-2 unit.

convert(value, other, ctype=<class 'numpy.float64'>, inplace=False)[source]

Converts a single value or NumPy array of values from the current unit to the other target unit.

If the units are not convertible, then no conversion will take place.

Args:

  • value (int/float/numpy.ndarray):
    Value/s to be converted.
  • other (string/Unit):
    Target unit to convert to.
  • ctype (cf_units.FLOAT32/cf_units.FLOAT64):
    Floating point 32-bit single-precision (cf_units.FLOAT32) or 64-bit double-precision (cf_units.FLOAT64) used for conversion when value is not a NumPy array or is a NumPy array composed of NumPy integers. The default is 64-bit double-precision conversion.
  • inplace (bool):
    If False, return a deep copy of the value array. If True, convert the values in-place. A new array will be created if value is an integer NumPy array.
Returns:
float or numpy.ndarray of appropriate float type.

For example:

>>> import cf_units
>>> import numpy as np
>>> c = cf_units.Unit('deg_c')
>>> f = cf_units.Unit('deg_f')
>>> c.convert(0, f)
31.999999999999886
>>> c.convert(0, f, cf_units.FLOAT32)
32.0
>>> a64 = np.arange(3, dtype=np.float64)
>>> c.convert(a64, f)
array([32. , 33.8, 35.6])
>>> a32 = np.arange(3, dtype=np.float32)
>>> c.convert(a32, f)
array([32. , 33.8, 35.6], dtype=float32)

Note

Conversion between unit calendars is not permitted unless the calendars are aliases, see cf_units.CALENDAR_ALIASES.

>>> from cf_units import Unit
>>> a = Unit('days since 1850-1-1', calendar='gregorian')
>>> b = Unit('days since 1851-1-1', calendar='standard')
>>> a.convert(365.75, b)
0.75
date2num(date)[source]

Returns the numeric time value calculated from the datetime object using the current calendar and unit time reference.

The current unit time reference must be of the form: ‘<time-unit> since <time-origin>’ i.e. ‘hours since 1970-01-01 00:00:00’

Works for scalars, sequences and numpy arrays. Returns a scalar if input is a scalar, else returns a numpy array.

Args:

  • date (datetime):
    A datetime object or a sequence of datetime objects. The datetime objects should not include a time-zone offset.
Returns:
float or numpy.ndarray of float.

For example:

>>> import cf_units
>>> import datetime
>>> u = cf_units.Unit('hours since 1970-01-01 00:00:00',
...                   calendar=cf_units.CALENDAR_STANDARD)
>>> u.date2num(datetime.datetime(1970, 1, 1, 5))
5.00000000372529
>>> u.date2num([datetime.datetime(1970, 1, 1, 5),
...             datetime.datetime(1970, 1, 1, 6)])
array([5., 6.])
definition

(read-only) The symbolic decomposition of the unit.

Formats the binary unit into a string representation using method cf_units.Unit.format() with keyword argument option=cf_units.UT_DEFINITION.

Returns:
string.

For example:

>>> import cf_units
>>> u = cf_units.Unit('watts')
>>> u.definition
'm2.kg.s-3'
format(option=None)[source]

Return a formatted string representation of the binary unit.

Args:

  • option (cf_units.UT_FORMATS):

    Set the option of the formatted string representation. Valid encoding options may be at most one of the following enumerations: * Unit.UT_ASCII * Unit.UT_ISO_8859_1 * Unit.UT_LATIN1 * Unit.UT_UTF8

    Any combination of the following may also be used: * Unit.UT_NAMES * Unit.UT_DEFINITION

    Multiple options may be combined within a list. The default option is cf_units.UT_ASCII.

Returns:
string.

For example:

>>> import cf_units
>>> u = cf_units.Unit('meters')
>>> u.format()
'm'
>>> u.format(cf_units.UT_NAMES)
'meter'
>>> u.format(cf_units.UT_DEFINITION)
'm'
invert()[source]

Invert the unit i.e. find the reciprocal of the unit, and return the Unit result.

Returns:
Unit.

For example:

>>> import cf_units
>>> u = cf_units.Unit('meters')
>>> u.invert()
Unit('m-1')
is_convertible(other)[source]

Return whether two units are convertible.

Args:

  • other (Unit): Unit to be compared.
Returns:
Boolean.

For example:

>>> import cf_units
>>> u = cf_units.Unit('meters')
>>> v = cf_units.Unit('kilometers')
>>> u.is_convertible(v)
True
is_dimensionless()[source]

Return whether the unit is dimensionless.

Returns:
Boolean.

For example:

>>> import cf_units
>>> u = cf_units.Unit('meters')
>>> u.is_dimensionless()
False
>>> u = cf_units.Unit('1')
>>> u.is_dimensionless()
True
is_long_time_interval()[source]

Defines whether this unit describes a time unit with a long time interval (“months” or “years”). These long time intervals are supported by UDUNITS2 but are not supported by cftime. This discrepancy means we cannot run self.num2date() on a time unit with a long time interval.

Returns:
Boolean.

For example:

>>> import cf_units
>>> u = cf_units.Unit('days since epoch')
>>> u.is_long_time_interval()
False
>>> u = cf_units.Unit('years since epoch')
>>> u.is_long_time_interval()
True
is_no_unit()[source]

Return whether the unit is defined to be a no_unit unit.

Typically, a quantity such as a string, will have no associated unit to describe it. Such a class of quantity may be defined using the no_unit unit.

Returns:
Boolean.

For example:

>>> import cf_units
>>> u = cf_units.Unit('no unit')
>>> u.is_no_unit()
True
>>> u = cf_units.Unit('meters')
>>> u.is_no_unit()
False
is_time()[source]

Determine whether this unit is a related SI Unit of time.

Returns:
Boolean.

For example:

>>> import cf_units
>>> u = cf_units.Unit('hours')
>>> u.is_time()
True
>>> v = cf_units.Unit('meter')
>>> v.is_time()
False
is_time_reference()[source]

Return whether the unit is a time reference unit of the form ‘<time-unit> since <time-origin>’ i.e. unit=’days since 1970-01-01 00:00:00’

Returns:
Boolean.

For example:

>>> import cf_units
>>> u = cf_units.Unit('days since epoch')
>>> u.is_time_reference()
True
is_udunits()[source]

Return whether the unit is a vaild unit of UDUNITS.

is_unknown()[source]

Return whether the unit is defined to be an unknown unit.

Returns:
Boolean.

For example:

>>> import cf_units
>>> u = cf_units.Unit('unknown')
>>> u.is_unknown()
True
>>> u = cf_units.Unit('meters')
>>> u.is_unknown()
False
is_vertical()[source]

Determine whether the unit is a related SI Unit of pressure or distance.

Returns:
Boolean.

For example:

>>> import cf_units
>>> u = cf_units.Unit('millibar')
>>> u.is_vertical()
True
>>> v = cf_units.Unit('km')
>>> v.is_vertical()
True
log(base)[source]

Returns the logorithmic unit corresponding to the given logorithmic base.

Args:

  • base (int/float): Value of the logorithmic base.
Returns:
None.

For example:

>>> import cf_units
>>> u = cf_units.Unit('meters')
>>> u.log(2)
Unit('lb(re 1 m)')
modulus

(read-only) Return the modulus value of the unit.

Convenience method that returns the unit modulus value as follows,
  • ‘radians’ - pi*2
  • ‘degrees’ - 360.0
  • Otherwise None.
Returns:
float.

For example:

>>> import cf_units
>>> u = cf_units.Unit('degrees')
>>> u.modulus
360.0
name

(read-only) The full name of the unit.

Formats the binary unit into a string representation using method cf_units.Unit.format() with keyword argument option=cf_units.UT_NAMES.

Returns:
string.

For example:

>>> import cf_units
>>> u = cf_units.Unit('watts')
>>> u.name
'watt'
num2date(time_value)[source]

Returns a datetime-like object calculated from the numeric time value using the current calendar and the unit time reference.

The current unit time reference must be of the form: ‘<time-unit> since <time-origin>’ i.e. ‘hours since 1970-01-01 00:00:00’

The datetime objects returned are ‘real’ Python datetime objects if the date falls in the Gregorian calendar (i.e. the calendar is ‘standard’, ‘gregorian’, or ‘proleptic_gregorian’ and the date is after 1582-10-15). Otherwise a ‘phoney’ datetime-like object (cftime.datetime) is returned which can handle dates that don’t exist in the Proleptic Gregorian calendar.

Works for scalars, sequences and numpy arrays. Returns a scalar if input is a scalar, else returns a numpy array.

Args:

  • time_value (float): Numeric time value/s. Maximum resolution is 1 second.
Returns:
datetime, or numpy.ndarray of datetime object.

For example:

>>> import cf_units
>>> u = cf_units.Unit('hours since 1970-01-01 00:00:00',
...                   calendar=cf_units.CALENDAR_STANDARD)
>>> u.num2date(6)
datetime.datetime(1970, 1, 1, 6, 0)
>>> u.num2date([6, 7])
array([datetime.datetime(1970, 1, 1, 6, 0),
       datetime.datetime(1970, 1, 1, 7, 0)], dtype=object)
offset_by_time(origin)[source]

Returns the time unit offset with respect to the time origin.

Args:

Returns:
None.

For example:

>>> import cf_units
>>> u = cf_units.Unit('hours')
>>> u.offset_by_time(cf_units.encode_time(1970, 1, 1, 0, 0, 0))
Unit('h @ 19700101T000000.0000000 UTC')
origin = None

The original string used to create this unit.

root(root)[source]

Returns the given root of the unit.

Args:

  • root (int): Value by which the unit root is taken.
Returns:
None.

For example:

>>> import cf_units
>>> u = cf_units.Unit('meters^2')
>>> u.root(2)
Unit('m')

Note

Taking a fractional root of a unit is not supported.

symbol

(read-only) The symbolic representation of the unit.

Formats the binary unit into a string representation using method cf_units.Unit.format().

Returns:
string.

For example:

>>> import cf_units
>>> u = cf_units.Unit('watts')
>>> u.symbol
'W'
title(value)[source]

Return the unit value as a title string.

Args:

  • value (float): Unit value to be incorporated into title string.
Returns:
string.

For example:

>>> import cf_units
>>> u = cf_units.Unit('hours since epoch',
...                   calendar=cf_units.CALENDAR_STANDARD)
>>> u.title(10)
'1970-01-01 10:00:00'
ut_unit = None

Reference to the quantity defining the UDUNITS-2 unit.

utime()[source]

Returns a cftime.utime object which performs conversions of numeric time values to/from datetime objects given the current calendar and unit time reference.

The current unit time reference must be of the form: ‘<time-unit> since <time-origin>’ i.e. ‘hours since 1970-01-01 00:00:00’

Returns:
cftime.utime.

For example:

>>> import cf_units
>>> u = cf_units.Unit('hours since 1970-01-01 00:00:00',
...                   calendar=cf_units.CALENDAR_STANDARD)
>>> ut = u.utime()
>>> ut.num2date(2)
datetime.datetime(1970, 1, 1, 2, 0, 0, 6)