我想找到最灵活的方式来输出两个日期之间的周数列表。
例如:
输入
start = datetime.date(2011, 12, 25)
end = datetime.date(2012, 1, 21)
输出
find_weeks(start, end)
>> [201152, 201201, 201202, 201203]
我一直在努力使用日期时间库而收效甚微
答案 0 :(得分:3)
某些内容(更新:删除了不太可读的选项)
import datetime
def find_weeks(start,end):
l = []
for i in range((end-start).days + 1):
d = (start+datetime.timedelta(days=i)).isocalendar()[:2] # e.g. (2011, 52)
yearweek = '{}{:02}'.format(*d) # e.g. "201152"
l.append(yearweek)
return sorted(set(l))
start = datetime.date(2011, 12, 25)
end = datetime.date(2012, 1, 21)
print(find_weeks(start,end)[1:]) # [1:] to exclude first week.
返回
['201152', '201201', '201202', '201203']
要包含第一周(201151),只需在函数调用后删除[1:]
答案 1 :(得分:2)
private void Button1_Click(object sender, RoutedEventArgs e)
{
Style style = new Style
{
TargetType = typeof(Window)
};
style.Setters.Add(new Setter(Window.BackgroundProperty, Brushes.Yellow));
Application.Current.Resources["MyStyle"] = style;
}
在这里是你的朋友 - 它会返回<Window x:Class="SimpleWpfPageApp.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SimpleWpfPageApp"
mc:Ignorable="d" Style="{DynamicResource MyStyle}"
的元组。我们使用它将开始日期重置为每周开始,然后每次添加一周,直到我们通过结束日期:
.isocalendar()
打印
(year, week of year, day of week)
答案 2 :(得分:1)
使用Pandas
import pandas as pd
dates=pd.date_range(start=start,end=end,freq='W')
date_index=dates.year.astype(str)+dates.weekofyear.astype(str).str.zfill(2)
date_index.tolist()
答案 3 :(得分:0)
我建议您使用以下易于阅读的解决方案:
import datetime
start = datetime.date(2011, 12, 25)
end = datetime.date(2012, 1, 21)
def find_weeks(start, end):
l = []
while (start.isocalendar()[1] != end.isocalendar()[1]) or (start.year != end.year):
l.append(start.isocalendar()[1] + 100*start.year)
start += datetime.timedelta(7)
l.append(start.isocalendar()[1] + 100*start.year)
return (l[1:])
print(find_weeks(start, end))
>> [201252, 201201, 201202, 201203]