#-*-coding:utf-8-*-
importdatetime
#给定日期向后N天的日期
defdateadd_day(days):
d1=datetime.datetime.now()
d3=d1+datetime.timedelta(days)
returnd3
#昨天
defgetYesterday():
today=datetime.date.today()
oneday=datetime.timedelta(days=1)
yesterday=today-oneday
returnyesterday
#今天
defgetToday():
returndatetime.date.today()
#获取给定参数的前几天的日期,返回一个list
defgetDaysBefore(num):
today=datetime.date.today()
oneday=datetime.timedelta(days=1)
li=[]
foriinrange(0,num):
#今天减一天,一天一天减
today=today-oneday
#把日期转换成字符串
li.append(datetostr(today))
returnli
#将字符串转换成datetime类型
defstrtodatetime(datestr,format):
returndatetime.datetime.strptime(datestr,format)
#时间转换成字符串,格式为2015-02-02
defdatetostr(date):
returnstr(date)[0:10]
#时间转换成字符串,格式为2015-02-02
defdatetostr_secod(date):
returnstr(date)[0:19]
#两个日期相隔多少天,例:2015-2-04和2015-3-1
defdatediff(beginDate,endDate):
format="%Y-%m-%d"
bd=strtodatetime(beginDate,format)
ed=strtodatetime(endDate,format)
oneday=datetime.timedelta(days=1)
count=0
whilebd!=ed:
ed=ed-oneday
count+=1
returncount
#两个日期之间相差的秒
defdatediff_seconds(beginDate,endDate):
format="%Y-%m-%d%H:%M:%S"
if""notinbeginDateor':'notinbeginDate:
bformat="%Y-%m-%d"
else:
bformat=format
if""notinendDateor':'notinendDate:
eformat="%Y-%m-%d"
else:
eformat=format
starttime=strtodatetime(beginDate,bformat)
endtime=strtodatetime(endDate,eformat)
ret=endtime-starttime
returnret.days*86400+ret.seconds
#获取两个时间段的所有时间,返回list
defgetDays(beginDate,endDate):
format="%Y-%m-%d"
begin=strtodatetime(beginDate,format)
oneday=datetime.timedelta(days=1)
num=datediff(beginDate,endDate)+1
li=[]
foriinrange(0,num):
li.append(datetostr(begin))
begin=begin+oneday
returnli
#获取当前年份是一个字符串
defgetYear(date=datetime.date.today()):
returnstr(date)[0:4]
#获取当前月份是一个字符串
defgetMonth(date=datetime.date.today()):
returnstr(date)[5:7]
#获取当前天是一个字符串
defgetDay(date=datetime.date.today()):
returnstr(date)[8:10]
#获取当前小时是一个字符串
defgetHour(date=datetime.datetime.now()):
returnstr(date)[11:13]
#获取当前分钟是一个字符串
defgetMinute(date=datetime.datetime.now()):
returnstr(date)[14:16]
#获取当前秒是一个字符串
defgetSecond(date=datetime.datetime.now()):
returnstr(date)[17:19]
defgetNow():
returndatetime.datetime.now()
printdateadd_day(10)
#2015-02-1416:41:13.275000
printgetYesterday()
#2015-02-03
printgetToday()
#2015-02-04
printgetDaysBefore(3)
#['2015-02-03','2015-02-02','2015-02-01']
printdatediff('2015-2-01','2015-10-05')
#246
printdatediff_seconds('2015-02-04','2015-02-05')
#86400
printdatediff_seconds('2015-02-0422:00:00','2015-02-05')
#7200
printgetDays('2015-2-03','2015-2-05')
#['2015-02-03','2015-02-04','2015-02-05']
printdatetostr_secod(getNow())
#2015-02-0416:46:47
printstr(getYear(dateadd_day(-50)))+'-'\
+getMonth()+'-'\
+getDay()+''\
+getHour()+':'\
+getMinute()+':'\
+getSecond()
#2014-02-0416:59:04
printgetNow()
#2015-02-0416:46:47.454000