python 获取昨天、今天、前天日期

获取查询 参数

def getFidByDate(fid):
yesterDate = getDatetimeYesterday()
params="from="+yesterDate +"&to="+yesterDate +"&fid="+str(fid)
url=monitorUrl+params
u=urllib2.urlopen(url)
jsonData=json.loads(u.read().decode('utf-8'))
return jsonData["result"]

得到今天日期

def getDatetimeToday():
t = date.today() #date类型
dt = datetime.strptime(str(t),'%Y-%m-%d') #date转str再转datetime
return dt

得到昨天日期

def getDatetimeYesterday():
today = getDatetimeToday() # datetime类型当前日期
yesterday = today + timedelta(days=-1) # 减去一天
return str(yesterday).split()[0]

得到前天日期

def getDatetimeQianTian():
today = getDatetimeToday() # datetime类型当前日期
qt = today + timedelta(days=-2) # 减去一天
return str(qt).split()[0]


Filename : test.py

author by : www.runoob.com

引入 datetime 模块

import datetime
def getYesterday():
today=datetime.date.today()
oneday=datetime.timedelta(days=1)
yesterday=today-oneday
return yesterday

输出

print(getYesterday())

日期和字符串互转

把datetime转成字符串

def datetime_toString(dt):
return dt.strftime("%Y-%m-%d-%H")

把字符串转成datetime

def string_toDatetime(string):
return datetime.strptime(string, "%Y-%m-%d-%H")

把字符串转成时间戳形式

def string_toTimestamp(strTime):
return time.mktime(string_toDatetime(strTime).timetuple())

把时间戳转成字符串形式

def timestamp_toString(stamp):
return time.strftime("%Y-%m-%d-%H", tiem.localtime(stamp))

把datetime类型转外时间戳形式

def datetime_toTimestamp(dateTim):
return time.mktime(dateTim.timetuple())

你可能感兴趣的:(python 获取昨天、今天、前天日期)