Import datetime, Calendar
Date = Datetime.datetime.now () Gets the current system time
#1, return to yesterday's date
Def getyesterday ():
Today=datetime.date.today ()
Oneday=datetime.timedelta (Days=1)
Yesterday=today-oneday
return yesterday
#2, return to today's date
Def gettoday ():
Return Datetime.date.today ()
#3, gets the date of the previous day of the given argument, returns a list
def getdaysbynum (num):
Today=datetime.date.today ()
Oneday=datetime.timedelta (Days=1)
Li=[]
For I in Range (0,num):
#今天减一天, day by day minus
Today=today-oneday
#把日期转换成字符串
#result =datetostr (today)
Li.append (Datetostr (today))
Return Li
#4, converting a string to a datetime type
def strtodatetime (Datestr,format):
Return Datetime.datetime.strptime (Datestr,format)
#5, time converted to string, formatted as 2008-08-02
def datetostr (date):
return str (date) [0:10]
#6, two days apart, for example: 2008-10-03 and 2008-10-01 are two days apart
def datediff (begindate,enddate):
format= "%y-%m-%d";
Bd=strtodatetime (Begindate,format)
Ed=strtodatetime (Enddate,format)
Oneday=datetime.timedelta (Days=1)
Count=0
While bd!=ed:
Ed=ed-oneday
Count+=1
return count
#7, gets all the time of two time periods, returns a list
def getDays (begindate,enddate):
format= "%y-%m-%d";
Bd=strtodatetime (Begindate,format)
Ed=strtodatetime (Enddate,format)
Oneday=datetime.timedelta (Days=1)
Num=datediff (begindate,enddate) +1
Li=[]
For I in Range (0,num):
Li.append (Datetostr (ed))
Ed=ed-oneday
Return Li
#8, gets the current year is a string
Def getYear ():
Return str (Datetime.date.today ()) [0:4]
#9, gets the current month is a string
Def getMonth ():
Return str (Datetime.date.today ()) [5:7]
#10, gets the current day is a string
Def getDay ():
Return str (Datetime.date.today ()) [8:10]
Def getnow ():
Return Datetime.datetime.now ()
Print Gettoday ()
Print Getyesterday ()
Print Getdaysbynum (3)
Print getDays (' 2008-10-01 ', ' 2008-10-05 ')
print ' 2008-10-04 00:00:00 ' [0:10]
Print str (getYear ()) +getmonth () +getday ()
Print Getnow ()
Python datetime module Basic usage