Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create date in python without time

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:
  ...................
like image 448
ruby student Avatar asked Aug 01 '15 04:08

ruby student


People also ask

How do I get the current date in Python without time?

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.

How do you make a date only in Python?

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.

What does date () do in Python?

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.


1 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
like image 52
Anand S Kumar Avatar answered Sep 19 '22 15:09

Anand S Kumar