gpt4 book ai didi

python - 检查日期是否在字符串中

转载 作者:太空宇宙 更新时间:2023-11-03 18:30:42 25 4
gpt4 key购买 nike

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

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) 进行比较?

最佳答案

一种方法是将您的 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

关于python - 检查日期是否在字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22431302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com