create date in python without time
In Python 3.9.5:
from datetime import datetime, time
datetime.combine(datetime.now(), time.min)
Which gives the result (if run on December 9, 2021):
datetime.date(2021, 12, 9)
which is a datetime object.
As Anand S. Kumar's reply states, you should use datetime.strptime() to convert the user provided date to a datetime object as well. Then you can do simple comparison for equality (==
), >
, <
, etc.
Please try: datetime.today().date()
Result: datetime.date(2021, 6, 26)
You can use datetime.date
objects , they do not have a time part.
You can get current date using datetime.date.today()
, Example -
now = datetime.date.today()
This would give you an object of type - datetime.date
. And you can get the date()
part of a datetime
object , by using the .date()
method , and then you can compare both dates.
Example -
now = datetime.date.today()
currentDate = datetime.datetime.strptime('01/08/2015','%d/%m/%Y').date()
Then you can compare them.
Also, to convert the string to a date , you should use datetime.strptime()
as I have used above , example -
currentDate = datetime.datetime.strptime('01/08/2015','%d/%m/%Y').date()
This would cause, currentDate
to be a datetime.date
object.
Example/Demo -
>>> now = datetime.date.today()
>>> currentDate = datetime.datetime.strptime('01/08/2015','%d/%m/%Y').date()
>>> now > currentDate
False
>>> now < currentDate
False
>>> now == currentDate
True