python计算两个日期间隔天数﹑周数和指定若干天后对应的日期

 1 >>> import datetime 
2 >>> help(datetime)
3 http://docs.python.org/library/datetime.html
4
5
6 查看2009年5月31日和2009年2月1日间隔多少天
7 >>> d1=datetime.date(2009,05,31)
8 >>> d2=datetime.date(2009,02,01)
9 >>> d1-d2
10 datetime.timedelta(119) // 可以看出2009年5月31日和2009年2月1日间隔为119天[luther.gliethttp].
11
12
13 查看2009年5月31日是今年的第几天和第几周
14 >>> d1=datetime.date(2009,05,31)
15 >>> d1.isocalendar()
16 (2009, 22, 7) // 2009年, 第22周, 礼拜7 [luther.gliethttp]
17 >>> d1.timetuple()
18 (2009, 5, 31, 0, 0, 0, 6, 151, -1) // (d.year, d.month, d.day, d.hour, d.minute, d.second, d.weekday(), 今年的第几天, dst)
19
20
21 查看2009年5月31日后第20周对应的日期
22 >>> d1=datetime.date(2009,05,31)
23 >>> d=datetime.timedelta(weeks=20) // 20周将被自动转化为天数[luther.gliethttp]
24 >>> d1+d
25 datetime.date(2009, 10, 18) // 所以2009年5月31日后第20周对应的日期为2009年10月18日[luther.gliethttp]
26
27
28 查看2009年5月31日后第100天对应的日期和90天之前的日期
29 >>> d1=datetime.date(2009,05,31)
30 >>> d=datetime.timedelta(days=100) // 100天
31 >>> d1+d
32 datetime.date(2009, 9, 8) // 所以2009年5月31日后第100天对应的日期为2009年9月8日[luther.gliethttp]
33 >>> d=datetime.timedelta(days=90)
34 >>> d1-d
35 datetime.date(2009, 3, 2) // 所以2009年5月31日向前数90天对应的日期为2009年3月2日[luther.gliethttp]
36
37
38 看看datetime.timedelta的使用小例子
39 datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
40 比如:
41 >>> datetime.timedelta(weeks=40, days=84, hours=23, minutes=50, seconds=600)
42 datetime.timedelta(365) // 使用timedelta()经过各种组合之后转化的总天数为365天[luther.gliethttp]
43 // 40*7 + 84 = 364
44 // 23时50分600秒=24时,所以为1天
45 // 故最终为364+1=365天[luther.gliethtp].
posted @ 2012-04-07 17:27  Goodpy  阅读(11990)  评论(0编辑  收藏  举报