Google Earth Engine Dates – How to Check if One Date Is Before or After Another in Google Earth Engine

datetimegoogle-earth-enginegoogle-earth-engine-python-api

How do I check if one date is before or after another date using the Google Earth Engine Python API?

In other words, I want to compare two dates like datetime object in Python.

import ee
firstDate=ee.Date.fromYMD(2022,3,2)
lastDay=ee.Date.fromYMD(2022,4,1)
# Compare if firstDate >= lastDate
firstDate>=lastDate

Best Answer

Your dates are server-side objects, that's why your client-side comparison fails. One option could be to avoid the creation of server-side dates to begin with, and rely on Python datetime.

Another option is to compare ee.Date.millis():

after = firstDate.millis().gte(lastDay.millis())

Note that while you could use ee.Algorithms.If() to do conditional logic based on these dates, it's something you should try to avoid.

When you come to a point where you feel you need a conditional, you typically can restructure your code to avoid it. You might filter a list or collection, or do some arithmetic tricks using the fact that firstDate.millis().gte(lastDay.millis()) returns 0 or 1. It's all very context dependent.

Related Question