7.Python的时间和日期

获取当前时间

1
2
3
4
5
6
7
>>> import time
>>> now=time.strftime('%Y-%m-%d %H:%M:%S')
>>> print now
2016-04-18 04:31:18
>>> today=time.strftime('%Y-%m-%d 00:00:00')
>>> print today
2016-04-18 00:00:00

获取前一天时间

1
2
3
4
>>> import datetime,time
>>> yesterday=datetime.datetime.now()+datetime.timedelta(days=-1)
>>> print yesterday.strftime('%Y-%m-%d %H:%M:%S') #格式化输出
2016-04-17 04:46:19

获取本月或者上月的某天

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env python
#coding=utf-8

def GetTime(x,y):
year = datetime.date.today().year
month = datetime.date.today().month
if month == 1 and y < 0:
month = 12
year -= 1
else:
month += y
return datetime.datetime(year,month,x).strftime('%Y-%m-%d %X')
# 本月25日
time1=GetTime(25,0)
# 上月25日
time2=GetTime(25,-1)