gpt4 book ai didi

Python-使用日期创建月份的周数列表

转载 作者:行者123 更新时间:2023-12-01 20:23:45 25 4
gpt4 key购买 nike

我有开始日期 ('2019-11-18') 和结束日期 ('2021-02-19')。我正在尝试创建一个列表,其中包含开始日期和结束日期之间存在的每个月的所有周。我的预期结果应该是这样的:

list = ['2019.Nov.3','2019.Nov.4', '2019.Nov.5' .... '2021.Feb.2','2021.Feb.3']

如果一个月的第一个或最后一个日期是星期三,我将假设该周属于本月(因为 5 个工作日中的 3 个工作日属于本月)

我实际上使用以下代码成功创建了一个包含一年中开始日期和结束日期之间存在的所有周的数据框:

date_1 = '18-11-19'

first_date = datetime.strptime(date_1, '%d-%m-%y')

date_2 = '19-02-21'

last_date = datetime.strptime(date_2, '%d-%m-%y')

timeline = pd.DataFrame(columns=['Year', 'Week'])


def create_list(df):
start_year = int(first_date.isocalendar()[0])
start_week = int(first_date.isocalendar()[1])
end_year = int(last_date.isocalendar()[0])
end_week = int(last_date.isocalendar()[1])

while start_year < (end_year + 1):

if start_year == end_year:

while start_week < (end_week + 1):

if len(str(start_week)) == 1:

week = f'{start_year}' + '.0' + f'{start_week}'

else:

week = f'{start_year}' + '.' + f'{start_week}'

df = df.append(({'Year': start_year, 'Week': week}), ignore_index=True)
start_week += 1

else:

while start_week < 53:

if len(str(start_week)) == 1:

week = f'{start_year}' + '.0' + f'{start_week}'

else:

week = f'{start_year}' + '.' + f'{start_week}'

df = df.append(({'Year': start_year, 'Week': week}), ignore_index=True)
start_week += 1

start_year += 1
start_week = 1

return df


timeline = create_list(timeline)

我成功地使用它作为我的折线图的 x 轴。然而,该轴有点难以阅读,并且很难知道哪一周属于哪一个月。

如果有人能帮我解决这个问题,我将非常感激!

编辑:

这是@Serge Ballesta 指导下的解决方案。我希望它对将来可能需要类似东西的人有所帮助!

import pandas as pd
import dateutil.relativedelta
from datetime import datetime


def year_week(date):
if len(str(date.isocalendar()[1])) == 1:

return f'{date.isocalendar()[0]}' + '.0' + f'{date.isocalendar()[1]}'

else:

return f'{date.isocalendar()[0]}' + '.' + f'{date.isocalendar()[1]}'


date_1 = '18-11-19'

first_date = datetime.strptime(date_1, '%d-%m-%y')

date_2 = '19-02-21'

last_date = datetime.strptime(date_2, '%d-%m-%y')

set_first_date = str((first_date - dateutil.relativedelta.relativedelta(months=1)).date())

set_last_date = str((last_date + dateutil.relativedelta.relativedelta(months=1)).date())

s = pd.date_range(set_first_date, set_last_date, freq='W-WED'
).to_series(name='wed').reset_index(drop=True)

df = s.to_frame()

df['week'] = df.apply(lambda x: year_week(x['wed']), axis=1)

df = df.assign(week_of_month=s.groupby(s.dt.strftime('%Y%m')
).cumcount() + 1)

df = df[(s >= pd.Timestamp('2019-11-18'))
& (s <= pd.Timestamp('2021-02-19'))]

df['month_week'] = (df['wed'].dt.strftime('%Y.%b.') + df['week_of_month'].astype(str)).tolist()

df = df.drop(['wed', 'week_of_month'], axis = 1)

print (df)

打印的df:

       week  month_week
4 2019.47 2019.Nov.3
5 2019.48 2019.Nov.4
6 2019.49 2019.Dec.1
7 2019.50 2019.Dec.2
8 2019.51 2019.Dec.3
.. ... ...
65 2021.03 2021.Jan.3
66 2021.04 2021.Jan.4
67 2021.05 2021.Feb.1
68 2021.06 2021.Feb.2
69 2021.07 2021.Feb.3

最佳答案

我将构建一系列频率为 W-WED 的时间戳,以始终将星期三作为一周中的某一天。这样,我们就能立即获得该周的正确月份。

要获得该月中的周数,我会在所需开始日期前一个月开始,并在年-月+1上使用cumcount。然后仅过滤就足够了预期范围并正确格式化值:

# produce a series of wednesdays starting in 2019-10-01
s = pd.date_range('2019-10-01', '2021-03-31', freq='W-WED'
).to_series(name='wed').reset_index(drop=True)

# compute the week number in the month
df = s.to_frame().assign(week_of_month=s.groupby(s.dt.strftime('%Y%m')
).cumcount() + 1)

# filter the required range
df = df[(s >= pd.Timestamp('2019-11-18'))
& (s <= pd.Timestamp('2021-02-19'))]

# here is the expected list
lst = (df['wed'].dt.strftime('%Y.%b.')+df['week_of_month'].astype(str)).tolist()

lst 符合预期:

['2019.Nov.3', '2019.Nov.4', '2019.Dec.1', '2019.Dec.2', '2019.Dec.3', '2019.Dec.4', 
'2020.Jan.1', '2020.Jan.2', '2020.Jan.3', '2020.Jan.4', '2020.Jan.5', '2020.Feb.1',
'2020.Feb.2', '2020.Feb.3', '2020.Feb.4', '2020.Mar.1', '2020.Mar.2', '2020.Mar.3',
'2020.Mar.4', '2020.Apr.1', '2020.Apr.2', '2020.Apr.3', '2020.Apr.4', '2020.Apr.5',
'2020.May.1', '2020.May.2', '2020.May.3', '2020.May.4', '2020.Jun.1', '2020.Jun.2',
'2020.Jun.3', '2020.Jun.4', '2020.Jul.1', '2020.Jul.2', '2020.Jul.3', '2020.Jul.4',
'2020.Jul.5', '2020.Aug.1', '2020.Aug.2', '2020.Aug.3', '2020.Aug.4', '2020.Sep.1',
'2020.Sep.2', '2020.Sep.3', '2020.Sep.4', '2020.Sep.5', '2020.Oct.1', '2020.Oct.2',
'2020.Oct.3', '2020.Oct.4', '2020.Nov.1', '2020.Nov.2', '2020.Nov.3', '2020.Nov.4',
'2020.Dec.1', '2020.Dec.2', '2020.Dec.3', '2020.Dec.4', '2020.Dec.5', '2021.Jan.1',
'2021.Jan.2', '2021.Jan.3', '2021.Jan.4', '2021.Feb.1', '2021.Feb.2', '2021.Feb.3']

关于Python-使用日期创建月份的周数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60548717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com