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:
...................
Let's say that you just want to extract the current date, without the 'time' portion. For example, you may want to display the date as: ddmmyyyy, where: dd would represent the day in the month.
Creating Date Objects To create a date, we can use the datetime() class (constructor) of the datetime module. The datetime() class requires three parameters to create a date: year, month, day.
The date class is used to instantiate date objects in Python. When an object of this class is instantiated, it represents a date in the format YYYY-MM-DD. Constructor of this class needs three mandatory arguments year, month and date.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With