[Dynamic Language] Python 取一年中某周的起始日期

Python 取一年中某周的起始日期,

思路:如果一年的第一天不是周一,则当前周为去年的最后一周,下周为本年的第一周。以当年的第一天在当前周中的索引为思路实现。

希望各位提供更好的思路。

1 #!/usr/bin/env python
2 # _#_ coding:utf-8 _*_
3
4 import datetime
5
6 current = datetime.datetime.now()
7 start = datetime.date(current.year,1,1)
8 start += datetime.timedelta(7 - start.weekday())
9
10 def print_date(i):
11 days = datetime.timedelta(weeks=i)
12 end = start + days
13 print i+1, end, end + datetime.timedelta(6)
15
16 def run():
17 for i in range(0, 53):
18 print_date(i)
19
20 if __name__ == "__main__":
21 run()

执行结果:

代码
abeen@localhost:~/learn_test$ ./test.py
1 2010-01-04 2010-01-10
2 2010-01-11 2010-01-17
3 2010-01-18 2010-01-24
4 2010-01-25 2010-01-31
5 2010-02-01 2010-02-07
6 2010-02-08 2010-02-14
7 2010-02-15 2010-02-21
8 2010-02-22 2010-02-28
9 2010-03-01 2010-03-07
10 2010-03-08 2010-03-14
11 2010-03-15 2010-03-21
12 2010-03-22 2010-03-28
13 2010-03-29 2010-04-04
14 2010-04-05 2010-04-11
15 2010-04-12 2010-04-18
16 2010-04-19 2010-04-25
17 2010-04-26 2010-05-02
18 2010-05-03 2010-05-09
19 2010-05-10 2010-05-16
20 2010-05-17 2010-05-23
21 2010-05-24 2010-05-30
22 2010-05-31 2010-06-06
23 2010-06-07 2010-06-13
24 2010-06-14 2010-06-20
25 2010-06-21 2010-06-27
26 2010-06-28 2010-07-04
27 2010-07-05 2010-07-11
28 2010-07-12 2010-07-18
29 2010-07-19 2010-07-25
30 2010-07-26 2010-08-01
31 2010-08-02 2010-08-08
32 2010-08-09 2010-08-15
33 2010-08-16 2010-08-22
34 2010-08-23 2010-08-29
35 2010-08-30 2010-09-05
36 2010-09-06 2010-09-12
37 2010-09-13 2010-09-19
38 2010-09-20 2010-09-26
39 2010-09-27 2010-10-03
40 2010-10-04 2010-10-10
41 2010-10-11 2010-10-17
42 2010-10-18 2010-10-24
43 2010-10-25 2010-10-31
44 2010-11-01 2010-11-07
45 2010-11-08 2010-11-14
46 2010-11-15 2010-11-21
47 2010-11-22 2010-11-28
48 2010-11-29 2010-12-05
49 2010-12-06 2010-12-12
50 2010-12-13 2010-12-19
51 2010-12-20 2010-12-26
52 2010-12-27 2011-01-02

原文地址:https://www.cnblogs.com/abeen/p/1875242.html