python - 如何在Python中连接日期?

标签 python python-3.x

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

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

有没有办法连接日期?

最佳答案

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

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']

关于python - 如何在Python中连接日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53530627/

相关文章:

python - 绘制排序的热图保持 (x,y) 值颜色

python - 如何按原样、反转和一次比较一个字符来比较两个两位数整数

python - 如何从类型别名中确定类型?

python - 不满足条件的第一个值的索引 Numpy

python - 使用 for 循环 Python 为数组赋值

python - 为什么我的 PanelND 工厂抛出 KeyError?

python - 检查 df1 中的字符串是否存在于 df2 中的任何位置,并返回 df1 中匹配的列名称

python - 与-Wl、-E 链接,这是什么意思等等?

django - 我想在 django 模型中添加一个位置字段,通过放置纬度和经度来获取位置输入

Python-firebase 与 firebase-storage 一起工作