Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't compare datetime.datetime to datetime.date

Tags:

python

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:

if not start or date < start: start = date 
like image 890
locoboy Avatar asked Aug 30 '11 06:08

locoboy


People also ask

Can we compare date with datetime?

Use datetime. datetime. date() can also be used to compare two dates. The datetime.

Can we compare datetime in Python?

When you have two datetime objects, the date and time one of them represent could be earlier or latest than that of other, or equal. To compare datetime objects, you can use comparison operators like greater than, less than or equal to.

How do I remove Tzinfo from datetime?

To remove timestamp, tzinfo has to be set None when calling replace() function. First, create a DateTime object with current time using datetime. now(). The DateTime object was then modified to contain the timezone information as well using the timezone.


2 Answers

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)

like image 123
juankysmith Avatar answered Oct 07 '22 15:10

juankysmith


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 
like image 33
Imran Avatar answered Oct 07 '22 16:10

Imran