【问题标题】:Get all week start dates in a month where week starts on specific day获取一周从特定日期开始的月份中的所有周开始日期
【发布时间】:2021-02-12 12:03:32
【问题描述】:

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

例如,如果当前日期是 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']

非常感谢

【问题讨论】:

  • 您的预期输出看起来不对...并非所有日期都是星期四。 [d.strftime("%F") for d in pd.date_range(dt.date(2021,2,1), dt.date(2021,2,28), freq="W-THU")]
  • 这只是一个人为的例子,用于演示。
  • 好的,那么上面的内容就可以工作了 - 每周星期四频率。无需自己编写代码

标签: python pandas datetime


【解决方案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 月 1 日是星期四,并且您希望您的列表从 1 月 1 日开始。修改了我的答案。现在更直观了..
  • 非常感谢,这样就解决了问题!
【解决方案2】:

我正在使用日历模块。

如果需要,您可以将输出用于 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']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-29
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多