检查日期是否为字符串

时间:2014-03-16 00:00:17

标签: python datetime

我有一个从表单返回的值字典:

planning_settings = {'days_clear': u'3', 'day_planned': u'0', 'dates_blocked': u'03/15/2014,03/16/2014,03/17/2014', 'star_method': u'1'}

我正在迭代一段时间:

for i in range( int(planning_settings['day_planned']), int(planning_settings['day_planned']) + 15 ):
    d = date.today() + timedelta(days=i)

我想检查d是否是在planning_settings ['dates_blocked']内的日期。我应该如何切割字符串u'03 / 15 / 2014,03 / 16 / 2014,03 / 17/2014'并将其与datetime.date对象进行比较,date.today()+ timedelta(days = i)?< / p>

1 个答案:

答案 0 :(得分:1)

一种方法是将您的datetime.date对象转换为字符串,然后检查该字符串是否在您的日期列表中(在逗号上拆分):

>>> from datetime import date, timedelta
>>> dates_blocked = u'03/15/2014,03/16/2014,03/17/2014'
>>> some_date = date.today() + timedelta(days=1)  # tomorrow
>>> some_date = date.strftime(some_date, '%m/%d/%Y')  # formats some_date into this format: 03/15/2014
>>> if some_date in dates_blocked.split(','):
    print some_date

03/16/2014

所以你的代码可能如下所示:

>>> planning_settings = {'days_clear': u'3', 'day_planned': u'0', 'dates_blocked': u'03/15/2014,03/16/2014,03/17/2014', 'star_method': u'1'}
>>> first_day = int(planning_settings['day_planned'])
>>> for i in range(first_day, first_day + 15):  # next two weeks
    d = date.today() + timedelta(days=i)
    d = date.strftime(d, '%m/%d/%Y')
    if d not in planning_settings['dates_blocked'].split(','):  # assumes you want available dates
        print d, 'available'


03/18/2014 available
03/19/2014 available
03/20/2014 available
03/21/2014 available
03/22/2014 available
03/23/2014 available
03/24/2014 available
03/25/2014 available
03/26/2014 available
03/27/2014 available
03/28/2014 available
03/29/2014 available