nylas/nylas-python

Cannot use timezone aware datetimes in messages API

Closed this issue · 3 comments

Hi,
I noticed that I cannot pass a timezone aware datetime object to the messages.where() API without getting a TypeError.

Steps to reproduce

>>> import datetime
>>> from nylas.client import APIClient
>>> client = APIClient(MY_CLIENT_ID, MY_SECRET, access_token=MY_ACCESS_TOKEN)
>>> after = datetime.datetime.fromisoformat('2020-03-31T06:50:23.756830+00:00')
>>> after
datetime.datetime(2020, 3, 31, 6, 50, 23, 756830, tzinfo=datetime.timezone.utc)
>>> for msg in client.messages.where(received_after=after):
...     print(msg.id)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/.../nylas/client/restful_model_collection.py", line 27, in values
    models = self._get_model_collection(offset, CHUNK_SIZE)
  File "/.../nylas/client/restful_model_collection.py", line 114, in _get_model_collection
    return self.api._get_resources(self.model_class, **filters)
  File "/.../nylas/client/client.py", line 320, in _get_resources
    filters, cls.datetime_filter_attrs
  File "/.../nylas/utils.py", line 28, in convert_datetimes_to_timestamps
    new_data[new_key] = timestamp_from_dt(value)
  File "/.../nylas/utils.py", line 10, in timestamp_from_dt
    delta = dt - epoch
TypeError: can't subtract offset-naive and offset-aware datetimes

Expected behaviour

I would assume that the API is either restricted to expecting UNIX timestamps only, or that it handles both aware and naive datetimes correctly. The current behaviour feels inconsistent to me:

  • client.messages.where(received_after=1585637423): works ✔️
  • client.messages.where(received_after=datetime.datetime(2020, 3, 31, 6, 50, 23)): works ✔️
  • client.messages.where(received_after=datetime.datetime(2020, 3, 31, 6, 50, 23, tzinfo=datetime.timezone.utc)): doesn't work ❌

Thanks for pointing this out @anneFly, We'll take a look at this.

@anneFly thanks for your submission, I'll take a look at this!

We added in an extra check now to ensure we safely convert an offset-aware datetime object before attempting to convert it to a timestamp. Should be available in the next release!