I need to get the current date without time and then compare that date with other entered by user
import datetime now = datetime.datetime.now() Example
currentDate="01/08/2015" userDate="01/07/2015" if currentData > userDate: ......... else: ................... 04 Answers
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 4If you want to compare dates, then compare dates, not strings. Use datetime.datetime.strptime() to parse the user's entered date.
import datetime now = datetime.datetime.now() userDate = "01/07/2015" if datetime.datetime.strptime(userDate, '%m/%d/%Y') < now: ... Please try: datetime.today().date()
Result: datetime.date(2021, 6, 26)
5In 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.