Search code examples
postgresqlredisredis-py

Storing postgresql timestamptz as score to redis sorted set via redis-py : DataError


I am storing postgresql timestamptz to redis sorted set using redis-py.

timestamptz is used as score and data is used as value.

I need the set to be sorted in descending order.But I can't insert the data into redis.I don't know how to convert into redis-supported format. Here's the code:

  cursor.execute("select current_timestamp;");
  timestamp_raw=cursor.fetchone()
  redis_client.zadd("stream",{data:timestamp_raw})

Error is below

.....\AppData\Local\Programs\Python\Python38-32\lib\site-packages\redis\connection.py", line 117, in encode
raise DataError("Invalid input of type: '%s'. Convert to a "redis.exceptions.DataError: Invalid input of type: 'tuple'. Convert to a byte, string or number first.

How to reslove it?


Solution

  • In Psycopg2, timestamptz is returned as a tuple of datetime and FixedOffsetTimezone.

    You need to convert the tuple to float so it can be used as a score.

    See Converting datetime.date to UTC timestamp in Python