Extract query returning Decimal('value'), float is expected

Question:

I saw a topic with the same question on Stackoverflow but I have a bit different question. My system locally return the value as float, but on GitHub Actions its Decimal. What could be the reason

session = app.ReadOnlySession()
query_ = text(query)
result_proxy = session.execute(query_, fetched_options)
res = result_proxy.fetchone()[0]
session.close()
if input_key in ["local_hour", "day_of_week"]:
    logger.info(f"ITS FOR TEST: {res=}")

Query:

SELECT EXTRACT(dow FROM now())
SELECT EXTRACT(hour FROM now())

GitHub:

ITS FOR TEST: res=Decimal('1')
ITS FOR TEST: res=Decimal('13')

Locally:

ITS FOR TEST: res=1.0 
ITS FOR TEST: res=13.0 

I want to have float return on GitHub

Asked By: Dmytryi Bernada

||

Answers:

This is due to a difference in PostgreSQL versions. Starting from PostgreSQL version 14, PostgreSQL returns values of type numeric for EXTRACT queries; previously it returned float8 (or double precision).

From the release notes:

Change EXTRACT() to return type numeric instead of float8 (Peter Eisentraut)

This avoids loss-of-precision issues in some usages. The old behavior can still be obtained by using the old underlying function date_part().

Psycopg2 represents float8 as a Python float but represents numeric as Decimal. As the release notes state, you can use date_part instead of extract if you want a float type returned.

Answered By: snakecharmerb