简体   繁体   English

通过在 python 中将日期递增一天来扩展日期列表

[英]Expand list of dates by incrementing dates by one day in python

In Python I have a list of dates as strings:在 Python 中,我有一个日期列表作为字符串:

dates = ['2022-01-01', '2022-01-08', '2022-01-21']

I would like to increment these dates by one day and add them to this list, like so:我想将这些日期增加一天并将它们添加到此列表中,如下所示:

dates_new = ['2022-01-01', '2022-01-02', '2022-01-08', '2022-01-09', '2022-01-21', '2022-01-22']

What is the best way to achieve this?实现这一目标的最佳方法是什么?

You will need to import a library:您将需要导入一个库:

import datetime

First convert the strings to dates using datetime.strptime .首先使用datetime.strptime将字符串转换为日期。 The important part of the code is the datetime.timedelta , is a function to sum days, month or years to a date.代码的重要部分是datetime.timedelta ,它是一个 function 用于将日期、月份或年份加到一个日期。 Create a new list to store the dates + 1, and then alternate the old date with the new date, that was calculated.创建一个新列表来存储日期 + 1,然后将旧日期与计算出的新日期交替使用。

dates = ['2022-01-01', '2022-01-08', '2022-01-21']
newDates = []

for date in dates:
    tempDate = datetime.datetime.strptime(date, '%Y-%m-%d')
    tempDate = tempDate + datetime.timedelta(days=1)
    tempDate = tempDate.strftime('%Y-%m-%d')
    newDates.append(date)
    newDates.append(tempDate)

print(newDates)

Result:结果:

['2022-01-01', '2022-01-02', '2022-01-08', '2022-01-09', '2022-01-21', '2022-01-22']

Try:尝试:

from datetime import datetime, timedelta

one_day = timedelta(days=1)
dates = ["2022-01-01", "2022-01-08", "2022-01-21"]

out = []
for d in dates:
    x = datetime.strptime(d, "%Y-%m-%d")
    out.append(d)
    out.append((x + one_day).strftime("%Y-%m-%d"))

print(out)

Prints:印刷:

['2022-01-01', '2022-01-02', '2022-01-08', '2022-01-09', '2022-01-21', '2022-01-22']

With datetime.timedelta class to get the needed difference/offset in days :使用datetime.timedelta class 以为单位获得所需的差异/偏移量:

from datetime import datetime, timedelta
from itertools import chain

dates = ['2022-01-01', '2022-01-08', '2022-01-21']
dates_inc = list(chain.from_iterable((d, str((timedelta(days=1) + datetime.strptime(d, "%Y-%m-%d")).date())) 
                                     for d in dates))
print(dates_inc)

['2022-01-01', '2022-01-02', '2022-01-08', '2022-01-09', '2022-01-21', '2022-01-22']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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