Problems filtering django datetime field by month and day

前端 未结 4 856
渐次进展
渐次进展 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.

提交回复
热议问题