如何在python中连接日期?

时间:2018-11-29 01:37:32

标签: python python-3.x

我想将特定时间段(即2017.08.15-2018.08.15)之间的日期连接起来,并且我希望它以字符串格式出现在列表或集合中:

("2017.08.15", "2017.08.16", ...)

是否可以串联日期?

2 个答案:

答案 0 :(得分:0)

不确定日期格式是否重要,但这是我解决问题的方法。希望这会有所帮助。

from datetime import date, timedelta


def get_dates(start_date, end_date):
    """
    :param start_date: date as a string ('YYYY.MM.DD')
    :param end_date: date as a string ('YYYY.MM.DD')
    :return: returns list of dates formatted as strings
    """
    # convert date as string to array of ints
    # i.e '2017.08.15 => [2017, 8, 15]
    start_date = map(int, start_date.split('.'))
    end_date = map(int, end_date.split('.'))

    # unpack array with date values into date objects
    start_date = date(*start_date)
    end_date = date(*end_date)

    # find difference between end_date and start
    delta = end_date - start_date

    # create list of dates between start_date and end_date
    dates = [start_date + timedelta(i) for i in range(delta.days + 1)]
    # format dates
    formatted_dates = [f'{date.year}.{date.month:02d}.{date.day:02d}' for date in dates]
    return formatted_dates


print(get_dates("2017.08.15", "2017.09.15"))

输出:

['2017.08.15', '2017.08.16', ... '2017.09.15']

答案 1 :(得分:0)

我查找了datetime模块,并得到了:

def get_dates():
    import datetime
    start_date = datetime.date(2015, 1, 1)
    end_date   = datetime.date(2016, 1, 1)
    date_range_list = []
    date_range = [ start_date + datetime.timedelta(n) for n in range(int ((end_date - start_date).days))]
    for date in date_range:
        date_range_list.append(str(date).replace("-","."))
    return(date_range_list)