Date Validator

  • To query the weather in a particular date, user need to input two parameters: location and date.

For date parameter, I need to check if the date value and format is valid.

  • Check the Value

    1. For the free version, Open Weather Map Daily API provides 16 days forecast.
    2. Thinkpage Daily API only provides 3 days(including today).

      So here, I'll set the valid date from today to today+2

    3. Use timedelta() to get the duration

      date.today() <= date <= date.today()+timedelta(days=2)
      
  • Convert the input date string to date object in a particular Format: %Y-%m-%d

    1. datetime.strptime(date_string, format) creates a datetime object from a string representing a date and time.
    2. datetime.date() converts datetime object to date object.
    3. If the input date string is not in '%Y-%m-%d ' format, it will raise a ValueError exception.

      try:
       date = datetime.strptime(date, '%Y-%m-%d').date()
      except ValueError:
       print('输入错误,时间格式为yyyy-mm-dd,请重新输入.')
      

So the entire function is as below:

from datetime import date
from datetime import timedelta
from datetime import datetime


def date_validator(date):
    '''validate the input date value and format'''
    try:
        date = datetime.strptime(date, '%Y-%m-%d').date()
    except ValueError:
        print('输入错误,时间格式为yyyy-mm-dd,请重新输入.')
        return False
    else:
        if date.today() <= date <= date.today()+timedelta(days=2):
            return True
        else:
            print('日期超出范围,仅可查询3日内天气预报,请重新输入!')
            return False

results matching ""

    No results matching ""