如何用Pandas的date_range获取从月初开始的周度数据?
Got it, you want to split the date range from 2015-07-01 to 2015-08-01 into weeks that start exactly on July 1st, instead of following pandas' default week boundaries (which is why your initial freq='W' gave you dates starting at 2015-07-05). Besides the timedelta or W-WED methods you already know, here are two simpler, more direct approaches:
方法一:用固定7天间隔freq='7D'
Since you explicitly want weeks starting on your custom start date, using 7D as the frequency parameter is the most straightforward solution. It generates dates strictly every 7 days starting from your initial date:
import pandas as pd custom_weekly_range = pd.date_range('2015-07-01', '2015-08-01', freq='7D') print(custom_weekly_range)
输出结果:
DatetimeIndex(['2015-07-01', '2015-07-08', '2015-07-15', '2015-07-22', '2015-07-29'], dtype='datetime64[ns]', freq='7D')
This perfectly aligns with your requirement—each entry marks the start of a new week, and all dates fall within your target range.
方法二:动态计算周期数生成
If you need more flexibility (like adjusting for variable date ranges), you can calculate the number of weeks first, then generate the range using the periods parameter:
import pandas as pd from datetime import datetime start_date = datetime(2015, 7, 1) end_date = datetime(2015, 8, 1) # Calculate total days and number of full weeks (plus the start day) total_days = (end_date - start_date).days num_weeks = total_days // 7 + 1 # +1 to include the starting date itself custom_weekly_range = pd.date_range(start=start_date, periods=num_weeks, freq='7D') print(custom_weekly_range)
This gives the exact same output as method one, and it's great for scenarios where your start/end dates might change dynamically.
Bonus: 获取完整周区间
If you need the full start-to-end range for each week (not just the start dates), you can easily derive them from the generated DatetimeIndex:
week_intervals = list(zip(custom_weekly_range, custom_weekly_range + pd.Timedelta(days=6))) for start, end in week_intervals: print(f"Week: {start.date()} to {end.date()}")
输出:
Week: 2015-07-01 to 2015-07-07 Week: 2015-07-08 to 2015-07-14 Week: 2015-07-15 to 2015-07-21 Week: 2015-07-22 to 2015-07-28 Week: 2015-07-29 to 2015-08-04
Note that the last week's end date goes beyond your original 2015-08-01—you can truncate it manually if needed.
内容的提问来源于stack exchange,提问作者lu5er

