获取一周在特定日期开始的月份中的所有周开始日期

时间:2021-02-11 17:11:57

标签: python pandas datetime

我需要创建一个所有周开始日期的列表,作为给定月份开始日期的字符串,该周从周四到周五。

例如,如果当前日期是 1 月 1 日星期一,我会从 12 月 28 日开始收集 1 月的一周开始日期。

到目前为止,我的方法成功地获得了给定月份中每周的开始日期,但是,结果是基于一周的开始作为星期一,而我需要它从上一个星期四开始:

import pandas as pd
from datetime import datetime, timedelta

month_start = '2021-02-01'
month_end = '2021-02-28'

dates = [
    d.strftime('%F') 
    for d in pd.date_range(month_start, month_end)
]

weeks = pd.Series(pd.to_datetime(dates)).apply(
    lambda x: (x - timedelta(days=x.dayofweek))).unique()

weeks = [
    w.strftime('%F') 
    for w in pd.to_datetime(weeks)
]

收益

<块引用> <块引用> <块引用>

['2021-02-01'、'2021-02-08'、'2021-02-15'、'2021-02-22']

预期结果:

<块引用> <块引用> <块引用>

['2021-01-28'、'2021-02-05'、'2021-02-11'、'2021-02-18'、'2021-02-25']

非常感谢

2 个答案:

答案 0 :(得分:1)

import pandas as pd
from datetime import datetime, timedelta 
def find_last_thursday(month_start: str):
    d = pd.to_datetime(month_start)
    return d - timedelta((d.dayofweek + 4)%7)
list(pd.date_range(start = find_last_thursday(month_start), end = month_end, freq='7D')\
.to_series().apply(datetime.strftime, format= "%F"))

答案 1 :(得分:0)

我正在使用日历模块。

如果需要,您可以将输出用于 Pandas。

代码在这里:

import calendar

a=calendar.Calendar()
month=2
year=2021

#last thursday last month
c=a.monthdatescalendar(year,month-1)
last_thursday_last_month=c[-1][3]

#all thursday this month
d=a.monthdatescalendar(year,month)
thursdays_this_month=[]
for x in d:
    thursdays_this_month.append(x[3])

all_thursdays = [last_thursday_last_month] + thursdays_this_month

b=[]
for item in all_thursdays:
    b.append(item.strftime("%Y-%m-%d"))

print(b)

执行时:

$ python3 getthursdays.py
['2021-01-28', '2021-02-04', '2021-02-11', '2021-02-18', '2021-02-25']