time constaint

111 views
Skip to first unread message

Prince K XAVIER

unread,
Nov 25, 2014, 9:29:21 AM11/25/14
to scitoo...@googlegroups.com
Hi all,

I thought it must be one of the most common requirements, but I never managed to find an example similar to my requirements. Maybe someone could help!

I want to apply a time constrain from [start_year, start_month, start_day] to [end_year, end_month, end_day]

I tried the following (with suggestions from https://groups.google.com/forum/#!msg/scitools-iris/znF7M48ifV4/t9KssLMtIxAJ ):

time_units = data.coord('time').units
start_val = time_units.date2num(datetime.datetime(start_year, start_month, start_day))
end_val = time_units.date2num(datetime.datetime(end_year, end_month, end_day))
time_constraint = iris.Constraint(time=lambda cell: start_val<=cell<=end_val)


but it fails with a not-so-helpful message:

File "model_main.py", line 135, in <lambda>
    time_constraint = iris.Constraint(time=lambda cell: start_val<=cell<=end_val)
  File "/opt/ukmo/iris/default/linux64/site-packages/iris/coords.py", line 311, in __ge__
    return self.__common_cmp__(other, operator.ge)
  File "/opt/ukmo/iris/default/linux64/site-packages/iris/coords.py", line 243, in __common_cmp__
    raise TypeError('Cannot determine the order of '
TypeError: Cannot determine the order of netcdftime.datetime objects

Could anyone suggest a simple way of doing this please?

Thanks,
Prince

Andrew Dawson

unread,
Nov 26, 2014, 8:35:13 AM11/26/14
to scitoo...@googlegroups.com
Hi Prince

You can do this quite simply by taking advantage of a relatively new feature that allows you to compare time coordinate points to datetime objects (although now that I think about it, it is maybe around a year old, what version of Iris are you using by the way?). You just need to do something like this (untested):

import iris
from datetime import datetime


iris
.FUTURE.cell_datetime_objects = True


start
= datetime(start_year, start_month, start_day) # define start/end_year/month/day somewhere
end = datetime(end_year, end_month, end_day)
time_constraint
= iris.Constraint(time=lambda c: start <= c <= end)


subset
= cube.extract(time_constraint)

Reply all
Reply to author
Forward
0 new messages