python實現時間的加減,類似linux的date命令
內容如題
原因:solaris等os不能做時間的運算處理,個人愛好。之前用c實現了一版,這裡再次用python實現一版,後期應該還有改進版
改進:1 程式碼最佳化
2 新增了指定獲取月份最後一天的功能
第四版:
新增了-d選項,-d date date_format,既可以指定時間字串和時間格式,格式可以不指定預設為 %Y%m%d或%Y-%m-%d
第五版:
1 修進了一些bug
2 把入口函式新增到類中,方便其他python的呼叫,而不是單純的指令碼
第六版:
在類中使用了初始化函式,方便呼叫,可以在初始化函式中直接設定需要輸入的引數,而不必對內部變數作出設定
第七版:
修改了-d引數從對時間戳的支援,例:-d "
1526606217
" "%s"
第八版:
修正版了部分程式碼,減少程式碼行數。
程式碼核心:
核心函式
datetime.datetime.replace()
calendar.monthrange()
datetime.timedelta()
核心思想:
不指定-l引數,不獲取計算後月份天數的最大值,既不獲取月份最後一天
月份加減主要是考慮當前日期天對比計算後的月份最大日期,如果大於計算後的日期天數,則在月份數+1,在日期天數上面替換為當前日期天數減去計算後的月份天數。例如:當前:2018-01-31,月份+1的話是2月,但是2月沒有31號,所以計算和的結果為2018-03-03,既月份+1為3,日期為31-28為3。
指定-l引數和不指定-l引數的不同點,在於月份的計算,指定-l引數則不會計算當前日期大於計算後的日期天數再次對月份和日期計算。例如,2018-01-31,不指定-l,月份+1,則結果會是2018-03-03,指定-l的結果則是2018-02-28。指定-l則是單純的在月份+1.
指令碼下載地址:
#!/usr/bin/env python # _*_coding:utf-8_*_ # Auth by raysuen # version v8.0 import datetime import time import calendar import sys import re # 時間計算的類 class DateColculation(object): rdate = { "time_tuple": time.localtime(), "time_format": "%Y-%m-%d %H:%M:%S %A", "colculation_string": None, "last_day": False, "input_time": None, "input_format": None } def __init__(self,time_tuple=None,out_format=None,col_string=None,isLastday=None,in_time=None,in_format=None): if time_tuple != None: self.rdate["time_tuple"] = time_tuple if out_format != None: self.rdate["time_format"] = out_format if col_string != None: self.rdate["colculation_string"] = col_string if isLastday != None: self.rdate["last_day"] = isLastday if in_time != None: self.rdate["input_time"] = in_time if in_format != None: self.rdate["input_format"] = in_format # 月計算的具體實現函式 def __R_MonthAdd(self, col_num, add_minus, lastday, time_truct): R_MA_num = 0 # 記錄計算的月的數字 R_ret_tuple = None # 返回值,None或者時間元組 R_MA_datetime = None # 臨時使用的datetime型別 if type(col_num) != int: # 判斷傳入的引數是否為數字 print("the parameter type is wrong!") exit(5) if time_truct == None: R_MA_datetime = datetime.datetime.now() # 獲取當前時間 else: R_MA_datetime = datetime.datetime.fromtimestamp(time.mktime(time_truct)) if add_minus.lower() == "add": # 判斷是否為+ R_MA_num = R_MA_datetime.month + col_num if R_MA_num > 12: # 判斷相加後的月份數是否大於12,如果大於12,需要在年+1 while R_MA_num > 12: R_MA_datetime = R_MA_datetime.replace(year=R_MA_datetime.year + 1) R_MA_num = R_MA_num - 12 R_ret_tuple = self.__days_add(R_MA_datetime, R_MA_num, lastday).timetuple() else: R_ret_tuple = self.__days_add(R_MA_datetime, R_MA_num, lastday).timetuple() elif add_minus.lower() == "minus": # 判斷是否為- while col_num >= 12: # 判斷傳入的引數是否大於12,如果大於12則對年做處理 R_MA_datetime = R_MA_datetime.replace(year=R_MA_datetime.year - 1) col_num = col_num - 12 # R_MA_num = 12 + (R_MA_datetime.month - col_num) # 獲取將要替換的月份的數字 if R_MA_datetime.month - col_num < 0: # 判斷當前月份數字是否大於傳入引數(取模後的),小於0表示,年需要減1,並對月份做處理 if R_MA_datetime.day > calendar.monthrange(R_MA_datetime.year - 1, R_MA_datetime.month)[ 1]: # 如果年減一後,當前日期的天數大於年減一後的天數,則在月份加1,天變更為當前日期天數減變更後的月份天數 R_MA_datetime = R_MA_datetime.replace(year=R_MA_datetime.year - 1, month=R_MA_datetime.month + 1, day=(R_MA_datetime.day > calendar.monthrange(R_MA_datetime.year - 1, R_MA_datetime.month)[1])) # 年減1 else: R_MA_datetime = R_MA_datetime.replace(year=R_MA_datetime.year - 1) # 年減1 R_MA_datetime = self.__days_add(R_MA_datetime, 12 - abs(R_MA_datetime.month - col_num), lastday) elif R_MA_datetime.month - col_num == 0: # 判斷當前月份數字是否等於傳入引數(取模後的),等於0表示,年減1,月份替換為12,天數不變(12月為31天,不可能會存在比31大的天數) R_MA_datetime = R_MA_datetime.replace(year=R_MA_datetime.year - 1, month=12) elif R_MA_datetime.month - col_num > 0: # 預設表示當前月份-傳入引數(需要減去的月數字)大於0,不需要處理年 R_MA_datetime = self.__days_add(R_MA_datetime, R_MA_datetime.month - col_num, lastday) R_ret_tuple = R_MA_datetime.timetuple() return R_ret_tuple # 返回時間元組 def __days_add(self, formal_MA_datetime, formal_MA_num, lastday): R_MA_datetime = formal_MA_datetime R_MA_num = formal_MA_num if lastday: # 如果計算月最後一天,則直接把月份替換,天數為月份替換後的最後一天 R_MA_datetime = R_MA_datetime.replace(month=R_MA_num, day=calendar.monthrange(R_MA_datetime.year, R_MA_num)[ 1]) # 月份替換,天數為替換月的最後一天 else: if R_MA_datetime.day > \ calendar.monthrange(R_MA_datetime.year, R_MA_num)[ 1]: # 判斷當前日期的天數是否大於替換後的月份天數,如果大於,月份在替換後的基礎上再加1,天數替換為當前月份天數減替換月份天數 R_MA_datetime = R_MA_datetime.replace(month=R_MA_num + 1, day=R_MA_datetime.day - calendar.monthrange(R_MA_datetime.year, R_MA_num)[ 1]) # 月份在替換月的數字上再加1,天數替換為當前月份天數減替換月份天數 else: R_MA_datetime = R_MA_datetime.replace(month=R_MA_num) # 獲取替換月份,day不變 return R_MA_datetime # 月計算的入口函式 def R_Month_Colculation(self, R_ColStr, lastday, time_truct): R_ret_tuple = None if R_ColStr.find("-") != -1: # 判斷-是否存在字串 col_num = R_ColStr.split("-")[-1].strip() # 獲取需要計算的數字 if col_num.strip().isdigit(): # 判斷獲取的數字是否為正整數 R_ret_tuple = self.__R_MonthAdd(int(col_num.strip()), "minus", lastday, time_truct) # 獲取tuple time時間格式 else: # 如果獲取的數字不為正整數,則退出程式 print("Please enter right format symbol!!") print("If you don't kown what values is avalable,please use -h to get help!") exit(4) elif R_ColStr.find("+") != -1: # 判斷+是否存在字串 col_num = R_ColStr.split("+")[-1].strip() # 獲取需要計算的數字 if col_num.strip().isdigit(): # 判斷獲取的數字是否為正整數 R_ret_tuple = self.__R_MonthAdd(int(col_num.strip()), "add", lastday, time_truct) # 獲取tuple time時間格式 else: print("Please enter right format symbol!!") print("If you don't kown what values is avalable,please use -h to get help!") exit(4) return R_ret_tuple # 秒,分,時,日,周計算的實現函式 def R_General_Colculation(self, R_ColStr, time_truct, cal_parm): R_ret_tuple = None if time_truct == None: # 判斷是否指定了輸入時間,沒指定則獲取當前時間,否則使用指定的輸入時間 R_Datatime = datetime.datetime.now() else: R_Datatime = datetime.datetime.fromtimestamp(time.mktime(time_truct)) if R_ColStr.find("-") != -1: # 判斷-是否存在字串 col_num = R_ColStr.split("-")[-1].strip() # 獲取需要計算的數字 if col_num.strip().isdigit(): # 判斷獲取的數字是否為正整數 if R_ColStr.strip().lower().find("second") != -1: R_ret_tuple = (R_Datatime + datetime.timedelta( seconds=-int(col_num.strip()))).timetuple() # 獲取tuple time時間格式 elif R_ColStr.strip().lower().find("minute") != -1: R_ret_tuple = (R_Datatime + datetime.timedelta( minutes=-int(col_num.strip()))).timetuple() # 獲取tuple time時間格式 elif R_ColStr.strip().lower().find("hour") != -1: R_ret_tuple = (R_Datatime + datetime.timedelta( hours=-int(col_num.strip()))).timetuple() # 獲取tuple time時間格式 elif R_ColStr.strip().lower().find("day") != -1: R_ret_tuple = (R_Datatime + datetime.timedelta( days=-int(col_num.strip()))).timetuple() # 獲取tuple time時間格式 elif R_ColStr.strip().lower().find("week") != -1: R_ret_tuple = (R_Datatime + datetime.timedelta( weeks=-int(col_num.strip()))).timetuple() # 獲取tuple time時間格式 # R_ret_tuple = (R_Datatime + datetime.timedelta(cal_parm=-int(col_num.strip()))).timetuple() # 獲取tuple time時間格式 else: # 如果獲取的數字不為正整數,則退出程式 print("Please enter right format symbol!!") print("If you don't kown what values is avalable,please use -h to get help!") exit(4) elif R_ColStr.find("+") != -1: # 判斷+是否存在字串 col_num = R_ColStr.split("+")[-1].strip() # 獲取需要計算的數字 if col_num.strip().isdigit(): # 判斷獲取的數字是否為正整數 if R_ColStr.strip().lower().find("second") != -1: R_ret_tuple = (R_Datatime + datetime.timedelta( seconds=int(col_num.strip()))).timetuple() # 獲取tuple time時間格式 elif R_ColStr.strip().lower().find("minute") != -1: R_ret_tuple = (R_Datatime + datetime.timedelta( minutes=int(col_num.strip()))).timetuple() # 獲取tuple time時間格式 elif R_ColStr.strip().lower().find("hour") != -1: R_ret_tuple = (R_Datatime + datetime.timedelta( hours=int(col_num.strip()))).timetuple() # 獲取tuple time時間格式 elif R_ColStr.strip().lower().find("day") != -1: R_ret_tuple = (R_Datatime + datetime.timedelta( days=int(col_num.strip()))).timetuple() # 獲取tuple time時間格式 elif R_ColStr.strip().lower().find("week") != -1: R_ret_tuple = (R_Datatime + datetime.timedelta( weeks=int(col_num.strip()))).timetuple() # 獲取tuple time時間格式 else: print("Please enter right format symbol!!") print("If you don't kown what values is avalable,please use -h to get help!") exit(4) return R_ret_tuple # 年計算的實現函式 def R_Year_Colculation(self, R_ColStr, time_truct): R_ret_tuple = None if time_truct == None: # 判斷是否指定了輸入時間,沒指定則獲取當前時間,否則使用指定的輸入時間 R_Y_Datatime = datetime.datetime.now() else: R_Y_Datatime = datetime.datetime.fromtimestamp(time.mktime(time_truct)) if R_ColStr.find("-") != -1: # 判斷-是否存在字串 col_num = R_ColStr.split("-")[-1].strip() # 獲取需要計算的數字 if col_num.strip().isdigit(): # 判斷獲取的數字是否為正整數 # 判斷當前時間是否為閏年並且為二月29日,如果是相加/減後不為閏年則在月份加1,日期加1 if calendar.isleap( R_Y_Datatime.year) and R_Y_Datatime.month == 2 and R_Y_Datatime.day == 29 and calendar.isleap( R_Y_Datatime.year - int(col_num.strip())) == False: R_ret_tuple = ( R_Y_Datatime.replace(year=R_Y_Datatime.year - int(col_num.strip()), month=R_Y_Datatime.month + 1, day=1)).timetuple() # 獲取tuple time時間格式 else: R_ret_tuple = ( R_Y_Datatime.replace( year=R_Y_Datatime.year - int(col_num.strip()))).timetuple() # 獲取tuple time時間格式 else: # 如果獲取的數字不為正整數,則退出程式 print("Please enter right format symbol!!") print("If you don't kown what values is avalable,please use -h to get help!") exit(4) elif R_ColStr.find("+") != -1: # 判斷+是否存在字串 col_num = R_ColStr.split("+")[-1].strip() # 獲取需要計算的數字 if col_num.strip().isdigit(): # 判斷獲取的數字是否為正整數 # 判斷當前時間是否為閏年並且為二月29日,如果是相加/減後不為閏年則在月份加1,日期加1 if calendar.isleap( R_Y_Datatime.year) and R_Y_Datatime.month == 2 and R_Y_Datatime.day == 29 and calendar.isleap( R_Y_Datatime.year + col_num.strip()) == False: R_ret_tuple = ( R_Y_Datatime.replace(year=R_Y_Datatime.year - int(col_num.strip()), month=R_Y_Datatime.month + 1, day=1)).timetuple() # 獲取tuple time時間格式 else: R_ret_tuple = ( R_Y_Datatime.replace( year=R_Y_Datatime.year + int(col_num.strip()))).timetuple() # 獲取tuple time時間格式 else: print("Please enter right format symbol!!") print("If you don't kown what values is avalable,please use -h to get help!") exit(4) return R_ret_tuple # 獲取月的最後一天 def R_Month_lastday(self, time_tuple): R_MA_datetime = datetime.datetime.fromtimestamp(time.mktime(time_tuple)) # time_tuple R_MA_datetime = R_MA_datetime.replace(day=(calendar.monthrange(R_MA_datetime.year, R_MA_datetime.month)[1])) return R_MA_datetime.timetuple() def R_colculation(self): ret_tupletime = None ColStr = self.rdate["colculation_string"] lastday = self.rdate["last_day"] input_time = None if ColStr != None: if type(ColStr) != str: print("Please enter right format symbol!!") print("If you don't kown what values is avalable,please use -h to get help!") exit(3) if (ColStr.find("-") != -1) and (ColStr.find("+") != -1): print("Please enter right format symbol!!") print("If you don't kown what values is avalable,please use -h to get help!") exit(3) if self.rdate["input_time"] != None: if self.rdate["input_format"] == None: i = 1 while 1: try: if i < 2: input_time = time.strptime(self.rdate["input_time"], "%Y%m%d") else: input_time = time.strptime(self.rdate["input_time"], "%Y-%m-%d") break except ValueError as e: if i < 2: i+=1 continue print("The input time and format do not match.") exit(98) elif self.rdate["input_format"] == "%s": if self.rdate["input_time"].isdigit(): input_time = time.localtime(int(self.rdate["input_time"])) else: print("The input time must be number.") exit(97) else: try: input_time = time.strptime(self.rdate["input_time"], self.rdate["input_format"]) except ValueError as e: print("The input time and format do not match.") exit(98) if lastday: if ColStr == None: if input_time != None: ret_tupletime = self.R_Month_lastday(input_time) else: ret_tupletime = self.R_Month_lastday(time.localtime()) # second的計算 # elif ColStr.strip().lower().find("second") != -1: # 判斷是否傳入的字串中是否存在hour關鍵字 # ret_tupletime = self.R_General_Colculation(ColStr.strip().lower(), input_time,"seconds") # # minute的計算 # elif ColStr.strip().lower().find("minute") != -1: # 判斷是否傳入的字串中是否存在hour關鍵字 # # ret_tupletime = self.R_Minute_Colculation(ColStr.strip().lower(), input_time) # ret_tupletime = self.R_General_Colculation(ColStr.strip().lower(), input_time, "minutes") # # hour的計算 # elif ColStr.strip().lower().find("hour") != -1: # 判斷是否傳入的字串中是否存在hour關鍵字 # # ret_tupletime = self.R_Hour_Colculation(ColStr.strip().lower(), input_time) # ret_tupletime = self.R_General_Colculation(ColStr.strip().lower(), input_time, "hours") # # day的計算 # elif ColStr.strip().lower().find("day") != -1: # 判斷是否傳入的字串中是否存在day關鍵字 # # ret_tupletime = self.R_Month_lastday(self.R_Day_Colculation(ColStr.strip().lower(), input_time)) # ret_tupletime = self.R_General_Colculation(ColStr.strip().lower(), input_time, "days") # # week的計算 # elif ColStr.strip().lower().find("week") != -1: # 判斷是否傳入的字串中是否存在day關鍵字 # # ret_tupletime = self.R_Month_lastday(self.R_Week_Colculation(ColStr.strip().lower(), input_time)) # ret_tupletime = self.R_General_Colculation(ColStr.strip().lower(), input_time, "weeks") elif ColStr.strip().lower().find("second") != -1 or ColStr.strip().lower().find("minute") != -1 or ColStr.strip().lower().find("hour") != -1 or ColStr.strip().lower().find("day") != -1 or ColStr.strip().lower().find("week") != -1: ret_tupletime = self.R_General_Colculation(ColStr.strip().lower(), input_time) # month的計算 elif ColStr.strip().lower().find("month") != -1: # 判斷是否傳入的字串中是否存在day關鍵字 ret_tupletime = self.R_Month_lastday(self.R_Month_Colculation(ColStr.strip().lower(), lastday, input_time)) # year的計算 elif ColStr.strip().lower().find("year") != -1: # 判斷是否傳入的字串中是否存在day關鍵字 ret_tupletime = self.R_Month_lastday(self.R_Year_Colculation(ColStr.strip().lower(), input_time)) else: print("Please enter right format symbol of -c.") print("If you don't kown what values is avalable,please use -h to get help!") exit(3) else: if ColStr == None: if self.rdate["input_time"] != None: ret_tupletime = input_time else: ret_tupletime = time.localtime() # second的計算 elif ColStr.strip().lower().find("second") != -1: # 判斷是否傳入的字串中是否存在hour關鍵字 ret_tupletime = self.R_General_Colculation(ColStr.strip().lower(), input_time, "seconds") # minute的計算 elif ColStr.strip().lower().find("minute") != -1: # 判斷是否傳入的字串中是否存在hour關鍵字 # ret_tupletime = self.R_Minute_Colculation(ColStr.strip().lower(), input_time) ret_tupletime = self.R_General_Colculation(ColStr.strip().lower(), input_time, "minutes") # hour的計算 elif ColStr.strip().lower().find("hour") != -1: # 判斷是否傳入的字串中是否存在hour關鍵字 # ret_tupletime = self.R_Hour_Colculation(ColStr.strip().lower(), input_time) ret_tupletime = self.R_General_Colculation(ColStr.strip().lower(), input_time, "hours") # day的計算 elif ColStr.strip().lower().find("day") != -1: # 判斷是否傳入的字串中是否存在day關鍵字 # ret_tupletime = self.R_Month_lastday(self.R_Day_Colculation(ColStr.strip().lower(), input_time)) ret_tupletime = self.R_General_Colculation(ColStr.strip().lower(), input_time, "days") # week的計算 elif ColStr.strip().lower().find("week") != -1: # 判斷是否傳入的字串中是否存在day關鍵字 # ret_tupletime = self.R_Month_lastday(self.R_Week_Colculation(ColStr.strip().lower(), input_time)) ret_tupletime = self.R_General_Colculation(ColStr.strip().lower(), input_time, "weeks") # month的計算 elif ColStr.strip().lower().find("month") != -1: # 判斷是否傳入的字串中是否存在day關鍵字 ret_tupletime = self.R_Month_Colculation(ColStr.strip().lower(), lastday, input_time) # year的計算 elif ColStr.strip().lower().find("year") != -1: # 判斷是否傳入的字串中是否存在day關鍵字 ret_tupletime = self.R_Year_Colculation(ColStr.strip().lower(), input_time) else: print("Please enter right format symbol of -c.") print("If you don't kown what values is avalable,please use -h to get help!") exit(3) return ret_tupletime def func_help(): print(""" NAME: rdate --display date and time SYNOPSIS: rdate [-f] [time format] [-c] [colculation format] [-d] [input_time] [input_time_format] DESCRIPTION: -c: value is hour/day/week/month/year,plus +/-,plus a number which is number to colculate -l: obtain a number which is last day of month -d: input_time: enter a time string input_time_format: enter a time format for input time,default %Y%m%d or %Y-%m-%d -f: %A is replaced by national representation of the full weekday name. %a is replaced by national representation of the abbreviated weekday name. %B is replaced by national representation of the full month name. %b is replaced by national representation of the abbreviated month name. %C is replaced by (year / 100) as decimal number; single digits are preceded by a zero. %c is replaced by national representation of time and date. %D is equivalent to ``%m/%d/%y''. %d is replaced by the day of the month as a decimal number (01-31). %E* %O* POSIX locale extensions. The sequences %Ec %EC %Ex %EX %Ey %EY %Od %Oe %OH %OI %Om %OM %OS %Ou %OU %OV %Ow %OW %Oy are supposed to provide alternate representations. Additionally %OB implemented to represent alternative months names (used standalone, without day mentioned). %e is replaced by the day of the month as a decimal number (1-31); single digits are preceded by a blank. %F is equivalent to ``%Y-%m-%d''. %G is replaced by a year as a decimal number with century. This year is the one that contains the greater part of the week (Monday as the first day of the week). %g is replaced by the same year as in ``%G'', but as a decimal number without century (00-99). %H is replaced by the hour (24-hour clock) as a decimal number (00-23). %h the same as %b. %I is replaced by the hour (12-hour clock) as a decimal number (01-12). %j is replaced by the day of the year as a decimal number (001-366). %k is replaced by the hour (24-hour clock) as a decimal number (0-23); single digits are preceded by a blank. %l is replaced by the hour (12-hour clock) as a decimal number (1-12); single digits are preceded by a blank. %M is replaced by the minute as a decimal number (00-59). %m is replaced by the month as a decimal number (01-12). %n is replaced by a newline. %O* the same as %E*. %p is replaced by national representation of either ante meridiem (a.m.) or post meridiem (p.m.) as appropriate. %R is equivalent to ``%H:%M''. %r is equivalent to ``%I:%M:%S %p''. %S is replaced by the second as a decimal number (00-60). %s is replaced by the number of seconds since the Epoch, UTC (see mktime(3)). %T is equivalent to ``%H:%M:%S''. %t is replaced by a tab. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number (00-53). %u is replaced by the weekday (Monday as the first day of the week) as a decimal number (1-7). %V is replaced by the week number of the year (Monday as the first day of the week) as a decimal number (01-53). If the week containing January 1 has four or more days in the new year, then it is week 1; otherwise it is the last week of the previous year, and the next week is week 1. %v is equivalent to ``%e-%b-%Y''. %W is replaced by the week number of the year (Monday as the first day of the week) as a decimal number (00-53). %w is replaced by the weekday (Sunday as the first day of the week) as a decimal number (0-6). %X is replaced by national representation of the time. %x is replaced by national representation of the date. %Y is replaced by the year with century as a decimal number. %y is replaced by the year without century as a decimal number (00-99). %Z is replaced by the time zone name. %z is replaced by the time zone offset from UTC; a leading plus sign stands for east of UTC, a minus sign for west of UTC, hours and minutes follow with two digits each and no delimiter between them (common form for RFC 822 date headers). %+ is replaced by national representation of the date and time (the format is similar to that produced by date(1)). %-* GNU libc extension. Do not do any padding when performing numerical outputs. %_* GNU libc extension. Explicitly specify space for padding. %0* GNU libc extension. Explicitly specify zero for padding. %% is replaced by `%'. EXAMPLE: rdate --2017-10-23 11:04:51 Monday rdate -f "%Y-%m_%d" --2017-10-23 rdate -f "%Y-%m_%d" -c "day-3" --2017-10-20 rdate -f "%Y-%m_%d" -c "day+3" --2017-10-26 rdate -f "%Y-%m_%d" -c "month+3" --2017-7-23 rdate -f "%Y-%m_%d" -c "year+3" --2020-7-23 rdate -c "week - 1" -f "%Y-%m-%d %V" --2018-02-15 07 rdate -c "day - 30" -f "%Y-%m-%d" -l --2018-01-31 rdate -d "1972-01-31" "%Y-%m-%d" --1972-01-31 00:00:00 Monday """) if __name__ == "__main__": d1 = DateColculation() if len(sys.argv) > 1: i = 1 while i < len(sys.argv): if sys.argv[i] == "-h": # 判斷輸入的引數是否為-h,既獲取幫助 func_help() exit(0) elif sys.argv[i] == "-f": # -f表示format,表示指定的輸出時間格式 i = i + 1 if i >= len(sys.argv): # 判斷-f的值的下標是否大於等於引數個數,如果為真則表示沒有指定-f的值 print("The value of -f must be specified!!!") exit(1) elif sys.argv[i] == "-c": print("The value of -f must be specified!!!") exit(1) elif re.match("^-", sys.argv[i]) != None: # 判斷-f的值,如果-f的下個引數以-開頭,表示沒有指定-f值 print("The value of -f must be specified!!!") exit(1) d1.rdate["time_format"] = sys.argv[i] # 獲取輸出時間格式 elif sys.argv[i] == "-c": # -c表示colculation,計算 i = i + 1 if i >= len(sys.argv): # 判斷-f的值的下標是否大於等於引數個數,如果為真則表示沒有指定-f的值 print("The value of -c must be specified!!!") exit(2) elif sys.argv[i] == "-f": print("The value of -c must be specified!!!") exit(2) elif (re.match("^-", sys.argv[i]) != None): # 判斷-f的值,如果-f的下個引數以-開頭,表示沒有指定-f值 print("The value of -c must be specified!!!") exit(2) d1.rdate["colculation_string"] = sys.argv[i] # 獲取需要計算的字串引數內容 elif sys.argv[i] == "-d": # -d date 表示指定輸入的時間和輸入的時間格式 i += 1 if i >= len(sys.argv): # 判斷-d的值的下標是否大於等於引數個數,如果為真則表示沒有指定-的值 print("The value of -d must be specified!!!") exit(3) elif (re.match("^-", sys.argv[i]) != None): # 判斷-d的值,如果-df的下個引數以-開頭,表示沒有指定-df值 print("The value of -c must be specified!!!") exit(3) d1.rdate["input_time"] = sys.argv[i] if (i+1 < len(sys.argv) and re.match("^-", sys.argv[(i+1)]) == None): d1.rdate["input_format"] = sys.argv[i+1] i+=1 elif sys.argv[i] == "-l": # -l表示獲取月份的最後一天 d1.rdate["last_day"] = True else: print("You must enter right parametr.") print("If you don't kown what values is avalable,please use -h to get help!") exit(3) i = i + 1 d1.rdate["time_tuple"] = d1.R_colculation() # 獲取時間的元組,透過R_colculation函式,R_colculation引數為傳入一個需要計算的時間字串 print(time.strftime(d1.rdate["time_format"], d1.rdate["time_tuple"])) exit(0) else: # 如果不輸入引數,則輸出預設格式化的本地時間 print(time.strftime(d1.rdate["time_format"], d1.rdate["time_tuple"])) exit(0)
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28572479/viewspace-2150704/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- js 轉化類似這樣的時間( /Date(1389060261000)/)問題JS
- golang 時間加減Golang
- linux 中 date命令的用法Linux
- linux的date命令設定Linux
- Linux date命令Linux
- Oracle計算時間函式(對時間的加減numtodsinterval、numtoyminterval)Oracle函式
- Java 時間類 Date、Calendar 及用法Java
- PostgreSQL類似OracleMERGE功能的實現SQLOracle
- 易優實現釋出時間顯示類似幾小時前、幾天前的效果
- 在dotnet core實現類似crontab的定時任務
- Linux 中date命令Linux
- Linux基礎命令—dateLinux
- Linux基礎命令---dateLinux
- MySQL 06 mysql 如何實現類似 oracle 的 merge intoMySqlOracle
- mysql查詢中時間、日期加減計算MySql
- JS設定時間格式為2010-01-01,以及時間加減JS
- MySQL實現當前資料表的所有時間都增加或減少指定的時間間隔(推薦)MySql
- 位運算實現加減乘除
- 【jquery】實現購物車加減jQuery
- Verilog實現加減乘除運算
- [Linux] Linux 自動掛載mount --bind 實現類似目錄硬鏈的效果 (包含ZFS方案)Linux
- 教你如何用SQLite 實現if not exist 類似功能的操作SQLite
- 用 golang 去實現類似 swoole 的 websocket 服務 ?GolangWeb
- 如何實現類似 lodash 的 get 與 merge 函式函式
- 使用函式RP_CALC_DATE_IN_INTERVAL進行日期的年月日的加減函式
- python 介面實現類的Python
- 直播系統程式碼,linux date修改系統時間Linux
- 深度解析:在 React 中實現類似 Vue 的 KeepAlive 元件ReactVue元件
- Blazor如何實現類似於微信的Tab切換?Blazor
- Laravel 小技巧 - 讓路由實現類似 Model::query 的效果Laravel路由
- 採用 SwiftNIO 實現一個類似 Express 的 Web 框架SwiftExpressWeb框架
- Struts框架 實現複數加減操作框架
- 譜聚類的python實現聚類Python
- 關於 Date 函式獲取各類時間/日期/天數函式
- 縮短 Linux 命令節省時間的四種方法Linux
- 常用的Linux命令;Linux常用命令用法及實現方式Linux
- WinForm使用DataGridView實現類似Excel表格的查詢替換ORMViewExcel
- Linux命令執行時間測試Linux
- flutter實現類似優惠券樣式Flutter