Alex McLean
Alex McLean

Reputation: 2764

Python: if date is passed or not logic with strings

In a large program that iterates over many many dates, I'm trying to process only dates that are passed (or at) a cutoff_date where date >= cutoff_date. This works great 99% of the time, however check out the following:

>>> print cutoff_date, type(cutoff_date)
2015-2-19 <type 'str'>
>>> a = '2015-3-20'
>>> a >= cutoff_date
True
>>> b = '2015-1-2'
>>> b >= cutoff_date
False
>>> c = '2015-2-9'
>>> c >= cutoff_date
True                     # I need this to be False ...
>>> d = '2015-2-09'
>>> d >= cutoff_date
False                    # ... just like this
>>> 

I know that I could set up a function where if the day of a date is one digit, add a 0 to the front of it. However I fear that this could screw up the rest of my code. Therefore before I go doing so, I'm wondering if threre is an easier way to solve this?

Upvotes: 1

Views: 82

Answers (3)

Shashank
Shashank

Reputation: 13869

>>> from datetime import datetime
>>> dateify = lambda ds: datetime.strptime(ds, '%Y-%m-%d')
>>> dateify('2015-2-19') > dateify('2015-2-18')
True
>>> dateify('2015-2-19') > dateify('2015-2-20')
False

Upvotes: 1

Klaus D.
Klaus D.

Reputation: 14369

To compare dates properly you have to make them DateTime or Date objects. To do that use datetime.datetime.strptime():

from datetime import datetime
d = datetime.strptime('2015-09-01', '%Y-%m-%d')
cut_off = datetime(2015, 9, 1)
if d >= cutoff:
    print('True')

Upvotes: 0

TigerhawkT3
TigerhawkT3

Reputation: 49318

Use the datetime module to work with dates, and strptime to parse strings that represent dates.

>>> import datetime
>>> cutoff = datetime.datetime.strptime('2015-2-19', '%Y-%m-%d')
>>> a = datetime.datetime.strptime('2015-3-20', '%Y-%m-%d')
>>> b = datetime.datetime.strptime('2015-1-2', '%Y-%m-%d')
>>> c = datetime.datetime.strptime('2015-2-9', '%Y-%m-%d')
>>> d = datetime.datetime.strptime('2015-2-09', '%Y-%m-%d')
>>> a>=cutoff
True
>>> b>=cutoff
False
>>> c>=cutoff
False
>>> d>=cutoff
False

Upvotes: 2

Related Questions