Django convert timestamp before performing a query?

Viewed 22

I have a unique instance where my front-end timestamp is generated based off of a user specific setting. (User can choose their timezeone, 12/24 hour clock).

I have a search feature in which a user can search based off of a timestamp.

The issue that I have is that my timestamp in the database is a UTC timestamp, but the user will want to search based off of the visual timestamp that they see on the page.

For example on the front-end of my application the timestamp shows...

2022-09-21 8:25:26 a.m.

Yet on the postgres side that timestamp will show as...

datetime.datetime(2022, 9, 21, 12, 25, 26, 959035, tzinfo=datetime.timezone.utc)

When a user types in 09-21, as expected, zero results get returned.

I am looking for a way to do convert time timestamp to the users timestamp before the query takes place, but not sure on the best solution, or right direction to to here. Any guidance would be greatly appreciated!

1 Answers

This is the flow. I assume your front-end Date input will be in string form. so you have to convert it to DateTime object and then convert its timezone to UTC. use that value to filter from DB. fetch data and if you're displaying that DateTime value in response then you have to convert it back to whatever timezone the user has. sharing pieces of code will help.

Convert your front-end string value to DateTime obj:

input_time = datetime.datetime.strptime(yourinput, "%d/%m/%Y %H:%M")

convert to your desired zone from UTC:

from_zone = tz.gettz("UTC")
to_zone = tz.gettz(timezone_info)("your required zone")
utctime = input_time.replace(tzinfo=from_zone)
new_time = utctime.astimezone(to_zone)

use this new_time in your Query fetch data if showing the date in the result convert it back to the desired zone after the query result and make it in string format like this.

time_format = "%d/%m/%Y %H:%M"
new_time = new_time.strftime(time_format)

Make sure to import required libraries

Related