Pravin Mishra
Pravin Mishra

Reputation: 31

Python logic without increasing much time complexity

I want to compare my dates without increasing much complexity and lines of code.

My date format is like this : '24-Jul-2019' start_date format is this:'2019-12-12'

But how can I compare such that this line is correct means the date comparison is correct for

data['Date'] > start_date and data['Date'] < end_date]

Note: I want to compare dates but my due to my dateformat it is showing error.

change_difference = [(data['High']- data['Low']) for data in dataset if data['Date'] > start_date and data['Date'] < end_date]

Upvotes: 0

Views: 176

Answers (1)

Felix
Felix

Reputation: 332

If I understand correctly, you want to compare dates. In your code, you do not seem to parse dates at all, which you can do like this:

from datetime import datetime

datestring_1 = "24-Jul-2019"
datestring_2 = "25-Jul-2019"
format = "%d-%b-%Y"
date_1 = datetime.strptime(datestring_1, format)
date_2 = datetime.strptime(datestring_2, format)
date_1 < date_2  # => True

In your applied case: Convert your variables data['Date'], start_date and end_date into datetimes. Once this is done, your comparison should work.

Note: Depending on your locale, you might have to make sure that the format is correct (see documentation)

Upvotes: 1

Related Questions