Reputation: 23
I am trying to write a python script that will compare dates from two different pages. The format of date in one page is Oct 03 2016 whereas on other page is (10/3/2016). My goal is to compare these two dates. I was able to convert Oct to 10 but don't know how to make it 10/3/2016.
Upvotes: 1
Views: 435
Reputation: 95948
You should really be using the dateutil
library for this.
>>> import dateutil.parser
>>> first_date = dateutil.parser.parse('Oct 03 2016')
>>> second_date = dateutil.parser.parse('10/3/2016')
>>> first_date
datetime.datetime(2016, 10, 3, 0, 0)
>>> second_date
datetime.datetime(2016, 10, 3, 0, 0)
>>> first_date == second_date
True
>>>
Upvotes: 6
Reputation: 48077
Use datetime
module to convert your string to datetime
object and then compare both. For example:
>>> from datetime import datetime
>>> date1 = datetime.strptime('Oct 03 2016', '%b %d %Y')
>>> date2 = datetime.strptime('10/3/2016', '%m/%d/%Y')
>>> date1 == date2
True
Further, you may convert thisdatetime
object to your custom format using datetime.strftime() as:
>>> date1.strftime('%d * %B * %Y')
'03 * October * 2016'
List of all the directives usable for formatting the string are available at the strftime
link I mentioned above.
Upvotes: 3