When processing log data, often to calculate the date, such as Date plus days, date difference days, the date of the week, etc., this article collects several commonly used Python date function, has been updated. Direct-Attach code (filename dateutil.py), function to view comments directly: #-*-Encoding:utf8-*- ''' @author: Crazyant @version: 2013-10-12 ''' Import datetime, Time #定义的日期的格式, you can change your own, such as "$Y year $m month $d Day" Format_date = "%y-%m-%d" Format_datetime = "%y-%m-%d%h:%m:%s" Def getcurrentdate (): ''' Get current date: 2013-09-10 such a date string ''' Return Time.strftime (Format_date, Time.localtime (Time.time ())) Def getcurrentdatetime (): ''' Get current time: 2013-09-10 11:22:11 time of the year month date time string ''' Return Time.strftime (Format_datetime, Time.localtime (Time.time ())) Def getcurrenthour (): ''' Gets the number of hours for the current time, such as 16 if the current is 16 o'clock in the afternoon ''' Currentdatetime=getcurrentdatetime () return currentdatetime[-8:-6] Def getdateelements (sdate): ' Enter a date string that returns a struct group containing the various components of the date Input: 2013-09-10 or 2013-09-10 22:11:22 Back: Time.struct_time (tm_year=2013, tm_mon=4, Tm_mday=1, tm_hour=21, tm_min=22, tm_sec=33, tm_wday=0, tm_yday=91, tm_ Isdst=-1) " Dformat =" " if Judgedateformat ( sdate) = = 0: return None elif Judgedateformat ( sdate) = = 1: dformat = format_date elif Judgedateformat (sdate) = = 2: dformat = format_datetime sdate = Time.strptime (sdate, Dformat) return sdate Def getdatetonumber (date1): ' remove the minus colon from the date string: Input: 2013-04-05, returning 20130405 input: 2013-04-05 22:11:23 returns 20130405221123 " return Date1.replace ("-"," "). Replace (": "," "). Replace (" "," ") def judgedateformat (DATESTR): ''' Determine the format of the date, if the "%y-%m-%d" format is returned 1, if it is "%y-%m-%d%h:%m:%s" then return 2, otherwise return 0 Parameter datestr: Date string ''' Try Datetime.datetime.strptime (Datestr, Format_date) Return 1 Except Pass Try Datetime.datetime.strptime (Datestr, Format_datetime) Return 2 Except Pass return 0 def minustwodate (Date1, Date2): ''' Subtract two dates to get the Datetime.timedelta object after subtraction The result can be accessed directly by its properties days, seconds, microseconds ''' If Judgedateformat (date1) = = 0 or Judgedateformat (date2) = = 0: Return None d1elements = getdateelements (date1) d2elements = getdateelements (date2) If not d1elements or not d2elements: Return None D1 = Datetime.datetime (D1elements.tm_year, D1elements.tm_mon, D1elements.tm_mday, D1elements.tm_hour, d1Elements.tm_ Min, d1elements.tm_sec) D2 = Datetime.datetime (D2elements.tm_year, D2elements.tm_mon, D2elements.tm_mday, D2elements.tm_hour, d2Elements.tm_ Min, d2elements.tm_sec) Return D1-D2 def dateaddindays (Date1, Addcount): ''' Date plus or minus a number to return a new date Parameter date1: the date to be calculated Parameter Addcount: The number to be added or subtracted, can be 1, 2, 3,-1,-2,-3, negative numbers to subtract ''' Try Addtime=datetime.timedelta (Days=int (Addcount)) D1elements=getdateelements (Date1) D1 = Datetime.datetime (D1elements.tm_year, D1elements.tm_mon, D1elements.tm_mday) Datenew=d1+addtime Return Datenew.strftime (format_date) Except Exception as E: Print E Return None Def is_leap_year (pyear): ' determine if the year entered is a leap years ' ' try: Datetime.datetime (pyear, 2) return true except valueerror: return false def datediffindays (Date1, Date2): ''' Gets the number of days between two dates, or negative numbers if date1 is greater than date2 and returns a positive value ''' Minusobj = Minustwodate (date1, Date2) Try Return minusobj.days Except Return None def datediffinseconds (Date1, Date2): ''' Gets the number of seconds that differ by two dates ''' Minusobj = Minustwodate (date1, Date2) Try Return minusobj.days * 3600 + minusobj.seconds Except Return None def getweekofdate (pdate): ''' Gets the week for the date, enters a date, returns a weekly number, 0~6, 0 of which is Sunday ''' Pdateelements=getdateelements (pdate) Weekday=int (Pdateelements.tm_wday) +1 If weekday==7: Weekday=0 Return weekday If __name__== "__main__": ''' Some test code ''' Print Judgedateformat ("2013-04-01") Print Judgedateformat ("2013-04-01 21:22:33") Print Judgedateformat ("2013-04-31 21:22:33") Print Judgedateformat ("2013-xx") Print "--" Print Datetime.datetime.strptime ("2013-04-01", "%y-%m-%d") print ' Elements ' Print getdateelements ("2013-04-01 21:22:33") print ' minus ' Print minustwodate ("2013-03-05", "2012-03-07"). Days Print Datediffinseconds ("2013-03-07 12:22:00", "2013-03-07 10:22:00") Print type (getcurrentdate ()) Print GetCurrentDateTime () Print Datediffinseconds (GetCurrentDateTime (), "2013-06-17 14:00:00") Print Getcurrenthour () Print Dateaddindays ("2013-04-05",-5) Print Getdatetonumber ("2013-04-05") Print Getdatetonumber ("2013-04-05 22:11:33") Print getweekofdate ("2013-10-01") |