check date range with only month and year in Python
Question: I only have `month` and `year`, and I want to compare if that **period** (of
an entire month) is between two `datetime` objects. For example if I have
these two dates:

    
    
    min_post_date = 2013-03-07 00:00:00
    max_post_date = 2014-01-01 00:00:00
    

And I only have year `2013`, and month `03`, it should give me `True`,
`02-2013` should give `False`, `04-2014` should give `False` and of course
`08-2013` should give `True`.

What would you recommend?

Thanks.


Answer: You can first compute the two dates at the beginning and the end of your
month:

    
    
    from calendar import monthrange
    from datetime import date, datetime
    
    begin = date(year, month, 1)
    end = date(year, month, monthrange(year, month)[1])
    

Then you can simply check that either `begin` or `end` fall within your range:

    
    
    (min_post_date <= begin <= max_post_date) or (min_post_date <= end <= max_post_date)
    

This is assuming that you parsed `min_post_date` and `max_post_date` with:

    
    
    min_post_date = datetime.strptime(min_post_date.split()[0], "%Y-%m-%d").date()
    

and similarly for `max_post_date`.

