Whenever I query a column representing a timestamp with timezone data, it returns a UTC datetime. Even when I update the timezone of the session with SET TIMEZONE <>, the output remains in UTC. I have a scenario in my FastAPI application where I need to dynamically change the timezone of the session based on the end user’s location. I use postgreSQL as my database.
Of course, using func.timezone(desired_timezone, column) will work, but are there other possible solutions? Also, adding func.timezone() to every single query feels tiresome, as most of the queries in my application involve timezone-aware columns.
Here’s a sample code reference
async def query_database():
"""Query the database and display timezone information."""
async with async_session_factory() as session:
for timezone in ["America/Toronto", "Europe/London"]:
await session.execute(text(f"SET TIME ZONE '{timezone}';"))
timezone_result = await session.scalar(text("SHOW TIMEZONE;"))
print(f"Current timezone: {timezone_result}")
entity = await session.scalar(select(TimezoneAwareModel))
print(f"Entity created at: {entity.created_at}")
This returns the following,
Current timezone: America/Toronto
Entity created at: 2024-07-15 10:49:07.182811+00:00
Current timezone: Europe/London
Entity created at: 2024-07-15 10:49:07.182811+00:00
Palaniyappan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3