short date in python (dd/mmm/yyyy)

Question:

I need to check a date by comparing it to today’s date but the format I am originally given is 12 Dec 2016.

I am not sure If I can even use pythons time modules to help me out with comparing it to the date of today because it is in a different format.

Asked By: nagrom97

||

Answers:

You can use the following:

from datetime import datetime

my_date = datetime.strptime('12 Dec 2016', '%d %b %Y')

Now, you can compare my_date with datetime.today()

Output:

>>> from datetime import datetime
>>>
>>> my_date = datetime.strptime('12 Dec 2016', '%d %b %Y')
>>>
>>> my_date
datetime.datetime(2016, 12, 12, 0, 0)
>>>
>>> my_date.date()
datetime.date(2016, 12, 12)
>>>
>>> datetime.today()
datetime.datetime(2016, 12, 16, 9, 44, 21, 562000)
>>> 
>>> datetime.today().date()
datetime.date(2016, 12, 16)
Answered By: ettanany

If you don’t know the format before hand you can use this:

from dateutil import parser
from datetime import datetime

print parser.parse("12 Dec 2016").date()
print datetime.now().date()
print parser.parse("12 Dec 2016").date() == datetime.now().date()

Output:

2016-12-12
2016-12-16
False
Answered By: Mohammad Yusuf
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.