I am aware of problems with filtering of date time in Django. That is why I build a raw Query Set:
query = 'SELECT * FROM meteorological_data_base.meteorological_data'
if year is not None:
query += ' WHERE EXTRACT(YEAR FROM date_time) = ' + year
if month is not None:
query += ' AND EXTRACT(MONTH FROM date_time) = ' + month
if day is not None:
query += ' AND EXTRACT(DAY FROM date_time) = ' + day
if hour is not None:
query += ' AND EXTRACT(HOUR FROM date_time) = ' + hour
meteorological_data_list = MeteorologicalData.objects.raw(query)
I am aware of SQL injection, this was written just for test. The problem is that I need Query Set because of Pagination. Now I tried this solution and it only works if I specify just the year part:
MeteorologicalData.objects.filter(date_time__year=2010)
If I also pass in month, then it returns empty Query Set:
MeteorologicalData.objects.filter(date_time__year=2010, date_time__month=1)
As I am using Django debug toolbar I can see what kind of SQL query does Django generate. And for the last example (year and month) it generated this:
SELECT COUNT(*) FROM `meteorological_data` WHERE (EXTRACT(MONTH FROM CONVERT_TZ(`meteorological_data`.`date_time`, 'UTC', 'Europe/Ljubljana')) = 1 AND `meteorological_data`.`date_time` BETWEEN '2009-12-31 23:00:00' and '2010-12-31 22:59:59')
I tried this in mysql console and it sure returns 0 rows. If I remove the CONVERT_TZ command:
SELECT COUNT(*) FROM `meteorological_data` WHERE (EXTRACT(MONTH FROM `meteorological_data`.`date_time`) = 1 AND `meteorological_data`.`date_time` BETWEEN '2009-12-31 23:00:00' and '2010-12-31 22:59:59')
It works as it should. Now I am using timezone aware date times. My configuration in settings:
TIME_ZONE = 'Europe/Ljubljana'
USE_TZ = True
So the end question is. How to use filter command that will not convert to timezone aware date time. The data is already stored in UTC format.
EDIT: Ok, I found out that the reason is missing TIMEZONE table in MySql. But still, how do I filter without conversion to TIMEZONE?