can't compare datetime.datetime to datetime.date

前端 未结 6 2026
野趣味
野趣味 2020-12-05 12:20

I have the following code and am getting the above error. Since I\'m new to python I\'m having trouble understanding the syntax here and how I can fix the error:

<         


        
相关标签:
6条回答
  • 2020-12-05 13:00

    This problem arises when you are trying to compare a date field (DateField) and a datetime field (DateTimeField).

    The solution would be check where you defined the fields in your models and ensure that the types are uniform.

    I would suggest you replace all DateField with DateTimeField.

    0 讨论(0)
  • 2020-12-05 13:10

    I was receiving the above error while using pandas, however, because the date_column was the string I wasted a lot of time without realizing I was formatting the wrong thing:

    # didnt work
    df[(df.date_column > parse_datestr('2018-01-01'))]
    
    # works
    df['date_column'] = pd.to_datetime(df['date_column'])
    df[(df.date_column > '2018-01-01') & (df.date_column < '2018-02-28')]
    
    0 讨论(0)
  • 2020-12-05 13:12

    Assuming start is a datetime, Use it like this:

    if not start or date < start.date(): start = date
    

    I don't think there is a need to convert date to datetime in python, as you can just do the opposite and compare.

    Or else you have other methods to create a new datetime by using the date to convert and time at 00:00.

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

    Your variables start and date are of different type I guess. One is a datetime and one is a date. You may have to show more code in order to get decent help.

    But look at this: http://docs.python.org/library/datetime.html#available-types

    It tells you that datetime.datetime has attributes like day, month and year, just like datetime.date.

    0 讨论(0)
  • 2020-12-05 13:21

    There is a datetime.date() method for converting from a datetime to a date.

    To do the opposite conversion, you could use this function datetime.datetime(d.year, d.month, d.day)

    0 讨论(0)
  • 2020-12-05 13:22

    You can use the datetime.datetime.combine method to compare the date object to datetime object, then compare the converted object with the other datetime object.

    import datetime
    
    dt1 = datetime.datetime(2011, 03, 03, 11, 12)
    day = datetime.date(2011, 03, 02)
    dt2 = datetime.datetime.combine(day, datetime.time(0, 0))
    
    print dt1 > dt2
    
    0 讨论(0)
提交回复
热议问题