Python日期操作

需求

把最近一周每天拍摄照片(探访人员)数目统计出来,数组形式返回。

需要的基本代码

日期格式转换

1
2
3
4
5
6
7
# data -> string
now = datetime.datetime.now()
now.strftime('%Y-%m-%d %H:%M:%S')

# string -> data
date_str = '2012-03-05 16:26:23'
date = datetime.datetime.strptime(t_str, '%Y-%m-%d %H:%M:%S')

日期比较

1
2
#所有的参数都有默认值0,这些参数可以是int或float,正的或负的
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

比如明天的日期

1
2
3
4
now = datetime.datetime.now()
delta = datetime.timedelta(days=1)
n_days = now + delta
print n_days.strftime('%Y-%m-%d %H:%M:%S')

SqlAlchemy中选择某个日期区间的值

1
2
3
4
today = datetime.datetime.now()
delta = datetime.timedelta(days=1)
tomorrow = now + delta
db.query.filter(time.between(today, tomorrow)).all()

实现

根据我的需求,我首先需要算出这个星期每一天。刚开始我用的代码这样的

1
2
3
4
5
6
7
8
from datetime import datetime, timedelta

NOW = datetime.now()

for d in range(7,0,-1):
left = (NOW - timedelta(days=d-1)).strftime('%m-%d')
right = (NOW - timedelta(days=d-2)).strftime('%m-%d')
print 'from %s to %s' %(left,right)

但经过运行得到结果如下

1
2
3
4
5
6
7
from 2015-03-11 15:18:08.831342 to 2015-03-12 15:18:08.831342
from 2015-03-12 15:18:08.831342 to 2015-03-13 15:18:08.831342
from 2015-03-13 15:18:08.831342 to 2015-03-14 15:18:08.831342
from 2015-03-14 15:18:08.831342 to 2015-03-15 15:18:08.831342
from 2015-03-15 15:18:08.831342 to 2015-03-16 15:18:08.831342
from 2015-03-16 15:18:08.831342 to 2015-03-17 15:18:08.831342
from 2015-03-17 15:18:08.831342 to 2015-03-18 15:18:08.831342

我做计算日期,应该是每天晚上0点到24点算为一天。所以改成如下模式,使获取的now为当天0点。

1
2
3
4
5
6
7
8
9
10
from dpythonatetime import datetime, timedelta

NOW = datetime.now()
NOW = NOW.strftime('%Y-%m-%d')
NOW = datetime.strptime(NOW, '%Y-%m-%d')

for d in range(7,0,-1):
left = (NOW - timedelta(days=d-1))
right = (NOW - timedelta(days=d-2))
print 'from %s to %s' %(left,right)

之后通过一下函数,来获取一周每天拍摄的次数。

1
2
3
4
5
6
7
8
9
10
11
def getWeeklyCount():
NOW = datetime.now()
NOW = NOW.strftime('%Y-%m-%d')
NOW = datetime.strptime(NOW, '%Y-%m-%d')
last_7d_count = []

for d in range(7,0,-1):#range(start,stop,step)
count = Piclist.query.filter(Piclist.time.between(NOW - timedelta(days=d-1), NOW - timedelta(days=d-2))).count()
thisday = (NOW - timedelta(days=d-1)).strftime('%m-%d')
last_7d_count.append([thisday,count])
return last_7d_count