Problems filtering django datetime field by month and day

前端 未结 4 848
渐次进展
渐次进展 2020-12-05 13:52

Can someone explain to me why the following filters are not working at the month and day level? Filtering by year seems to work, but not the other two.

>         


        
相关标签:
4条回答
  • 2020-12-05 14:26

    To update the answer here since I ran into the above issue but none of the solutions worked. Most new mysql installations come pre-installed with tz-info, so the mysql_tzinfo_to_sql command wont really help. And setting TZ_INFO to False isn't really a solution since many need time-zone aware datetime.

    So, what worked for me was to create a tz aware datetime object and check against that. Lets say you wanna filter records for today you would do something like,

    from datetime import datetime
    import pytz
    
    today = datetime.now().replace(tzinfo=pytz.UTC).date()   # tz aware datetime object
    todays_records = myModel.objects.filter(created__year=today.year, created__month=today.month,created__day=today.day)
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-05 14:37

    Your syntax is incorrect. It should be:

    Clicks.objects.filter(created__month=2)
    

    (you left off the 'objects' manager)

    0 讨论(0)
  • 2020-12-05 14:38

    @Simon Wilder perfectly answer why it's not working, here is how you can actually solve it without disabling TZ support in django

    Django document give instruction to install time zone definition to database:

    SQLite: install pytz — conversions are actually performed in Python.

    PostgreSQL: no requirements (see Time Zones).

    Oracle: no requirements (see Choosing a Time Zone File).

    MySQL: install pytz and load the time zone tables with mysql_tzinfo_to_sql.

    In my case : mysql and Mac Os, following command solve the problem:

    sudo mysql_tzinfo_to_sql /usr/share/zoneinfo/ | mysql -u root mysql
    
    0 讨论(0)
  • 2020-12-05 14:44

    I was seeing exactly the same behaviour as you.

    If you check the documentation for 1.6 and the month queryset. They have added the following paragraph:

    "When USE_TZ is True, datetime fields are converted to the current time zone before filtering. This requires time zone definitions in the database."

    If you change the following line in your settings to False, then you should start getting the data back that you're expecting.

    USE_TZ = False
    
    0 讨论(0)
提交回复
热议问题