试图减去两个日期以查找中间的天数

时间:2016-08-19 15:28:11

标签: python datetime zapier

在Zapier,我有两个约会,我正试图在代码步骤中查找它们之间的天数。我在每个日期运行Formatter Step以在YYYY-MM-DD中输出datetime对象,然后运行以下代码:

submit = input['submit_date']
event = input['event_date']
delta = event-submit
numdays = delta.days

return {'numdays': numdays}

我得到的错误表明我导入的两个日期是字符串,而不是日期时间。

这是错误:

Your code had an error! Traceback (most recent call last): File "/tmp/tmp7xyg3Z/usercode.py", line 10, in the_function delta = event-submit TypeError: unsupported operand type(s) for -: 'unicode' and 'unicode'

任何人都知道我做错了什么或更好的方法来完成这项任务?

3 个答案:

答案 0 :(得分:3)

格式化程序步骤不包含在内,但通常您需要时间或日期时间对象(import timeimport datetime

您可能应该从datetime选项中查看datetime.strptime(date_string, format)之类的内容,以获取文本字符串并将其转换为日期/时间对象。

https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

答案 1 :(得分:0)

我有两种方法get_days(start_date, end_date)increment_da_day(str_date)

调用get_days()它会返回一个天数列表(格式为yyyymmdd),您可以提供开始日期和结束日期并打印get_days(start_date, end_date) - 1

例如:

导入日期时间

def get_days(start_date, end_date):
    """returns a list of days"""
    all_days = []
    starts = start_date
    all_days.append(starts)

    while int(starts) < int(end_date):
        starts = increment_a_day(starts)
        all_days.append(starts)
    return all_days

def increment_a_day(str_date):
    """increments a day for given date string in format yyyymmdd"""
    year = int(str_date[:4])
    month = int(str_date[4:6])
    day = int(str_date[-2:])

    now = datetime.date(year, month, day)
    delta = datetime.timedelta(days=1)
    return (now + delta).strftime('%Y%m%d') #yyyymmdd

您只需要执行以下操作:

days = get_days("20160601", "20160602")

delta =  len(days) - 1
print delta

答案 2 :(得分:0)

如果它们是字符串,您可以传递输入或在那里输入输入,以下代码将返回日期

def h():
    from datetime import datetime
    date_format = "%m/%d/%Y"
    a = datetime.strptime(input('Enter first date in MM/DD/YY format '), date_format)
    b = datetime.strptime(input('Enter second date in MM/DD/YY format '), date_format)
    delta = b - a
    print (delta.days)
    return int(delta.days)

a='8/18/2008'
b='9/26/2008'
def h(c,d):
    from datetime import datetime
    date_format = "%m/%d/%Y"
    a = datetime.strptime(c, date_format)
    b = datetime.strptime(d, date_format)
    delta = b - a
    print (delta.days)
    return int(delta.days)