简体   繁体   中英

How can I concatenate dates in python?

I want to concatenate dates between a specific time period, ie 2017.08.15 - 2018.08.15, and I want this in string formats in a list or a set:

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

Is there a way to concatenate dates?

Wasn't sure if the date formatting was important, but here is my approach to the problem. Hope this is helpful.

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"))

Output:

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

I looked up the datetime module, and got this:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM