通过迭代减去日期来重命名列

时间:2019-05-23 01:42:10

标签: python

我有CSV列,例如New_01,New_02到New_106。 我想通过减去7天来重命名列,并迭代获取日期。

默认情况下,日期从New_01 = 2019年4月19日开始

例如,

If New_01 = April 19, 2019

then New_02 = April 12, 2019

New_03 = April 5, 2019 . . . . . likewise

有没有办法使用Python?我不知道从哪里开始。

1 个答案:

答案 0 :(得分:0)

使用datetime.datetimedatetime.timedelta

from datetime import datetime, timedelta

columns = ['New_%s' % str(i).zfill(2) for i in range(1,107)]
fmt = '%B %d, %Y'
start_date = 'April 19, 2019'
current = datetime.strptime(start_date, fmt)
date_columns = [datetime.strftime(current - timedelta(days = 7 * i), fmt) for i, _ in enumerate(columns)]

输出:

['April 19, 2019',
 'April 12, 2019',
 'April 05, 2019',
 'March 29, 2019',
 'March 22, 2019',
 'March 15, 2019',
 'March 08, 2019',
 'March 01, 2019',
 'February 22, 2019',
 'February 15, 2019',
 'February 08, 2019',
 ...
]

如果您希望保留其他格式的列:

date_columns = []
i = 0
for c in columns:
    if c.startswith('New'):
        date_columns.append(datetime.strftime(current - timedelta(days = 7 * i), fmt))
        i += 1
    else:
        date_columns.append(c)