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.

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # _*_coding:utf8_*_
  3. # Auth by raysuen
  4. # version v7.0
  5. import datetime
  6. import time
  7. import calendar
  8. import sys
  9. import re
  10. # 时间计算的类
  11. class DateColculation(object):
  12.     rdate = {
  13.         “time_tuple”: time.localtime(),
  14.         “time_format”: “%Y-%m-%d %H:%M:%S %A”,
  15.         “colculation_string”: None,
  16.         “last_day”: False,
  17.         “input_time”: None,
  18.         “input_format”: None
  19.     }
  20.     def __init__(self,time_tuple=None,out_format=None,col_string=None,isLastday=None,in_time=None,in_format=None):
  21.         if time_tuple != None:
  22.             self.rdate[“time_tuple”] = time_tuple
  23.         if out_format != None:
  24.             self.rdate[“time_format”] = out_format
  25.         if col_string != None:
  26.             self.rdate[“colculation_string”] = col_string
  27.         if isLastday != None:
  28.             self.rdate[“last_day”] = isLastday
  29.         if in_time != None:
  30.             self.rdate[“input_time”] = in_time
  31.         if in_format != None:
  32.             self.rdate[“input_format”] = in_format
  33.     # 月计算的具体实现函数
  34.     def __R_MonthAdd(self, col_num, add_minus, lastday, time_truct):
  35.         R_MA_num = 0 # 记录计算的月的数字
  36.         R_ret_tuple = None # 返回值,None或者时间元组
  37.         R_MA_datetime = None # 临时使用的datetime类型
  38.         if type(col_num) != int: # 判断传入的参数是否为数字
  39.             print(“the parameter type is wrong!”)
  40.             exit(5)
  41.         if time_truct == None:
  42.             R_MA_datetime = datetime.datetime.now() # 获取当前时间
  43.         else:
  44.             R_MA_datetime = datetime.datetime.fromtimestamp(time.mktime(time_truct))
  45.         if add_minus.lower() == “add”: # 判断是否为+
  46.             R_MA_num = R_MA_datetime.month + col_num
  47.             if R_MA_num > 12: # 判断相加后的月份数是否大于12,如果大于12,需要在年+1
  48.                 while R_MA_num > 12:
  49.                     R_MA_datetime = R_MA_datetime.replace(year=R_MA_datetime.year + 1)
  50.                     R_MA_num = R_MA_num 12
  51.                 R_ret_tuple = self.__days_add(R_MA_datetime, R_MA_num, lastday).timetuple()
  52.             else:
  53.                 R_ret_tuple = self.__days_add(R_MA_datetime, R_MA_num, lastday).timetuple()
  54.         elif add_minus.lower() == “minus”: # 判断是否为
  55.             while col_num >= 12: # 判断传入的参数是否大于12,如果大于12则对年做处理
  56.                 R_MA_datetime = R_MA_datetime.replace(year=R_MA_datetime.year 1)
  57.                 col_num = col_num 12
  58.             # R_MA_num = 12 + (R_MA_datetime.month col_num) # 获取将要替换的月份的数字
  59.             if R_MA_datetime.month col_num < 0: # 判断当前月份数字是否大于传入参数(取模后的),小于0表示,年需要减1,并对月份做处理
  60.                 if R_MA_datetime.day > calendar.monthrange(R_MA_datetime.year 1, R_MA_datetime.month)[
  61.                     1]: # 如果年减一后,当前日期的天数大于年减一后的天数,则在月份加1,天变更为当前日期天数减变更后的月份天数
  62.                     R_MA_datetime = R_MA_datetime.replace(year=R_MA_datetime.year 1, month=R_MA_datetime.month + 1,
  63.                                                           day=(R_MA_datetime.day >
  64.                                                                calendar.monthrange(R_MA_datetime.year 1,
  65.                                                                                    R_MA_datetime.month)[1])) # 年减1
  66.                 else:
  67.                     R_MA_datetime = R_MA_datetime.replace(year=R_MA_datetime.year 1) # 年减1
  68.                 R_MA_datetime = self.__days_add(R_MA_datetime, 12 abs(R_MA_datetime.month col_num), lastday)
  69.             elif R_MA_datetime.month col_num == 0: # 判断当前月份数字是否等于传入参数(取模后的),等于0表示,年减1,月份替换为12,天数不变(12月为31天,不可能会存在比31大的天数)
  70.                 R_MA_datetime = R_MA_datetime.replace(year=R_MA_datetime.year 1, month=12)
  71.             elif R_MA_datetime.month col_num > 0: # 默认表示当前月份传入参数(需要减去的月数字)大于0,不需要处理年
  72.                 R_MA_datetime = self.__days_add(R_MA_datetime, R_MA_datetime.month col_num, lastday)
  73.             R_ret_tuple = R_MA_datetime.timetuple()
  74.         return R_ret_tuple # 返回时间元组
  75.     def __days_add(self, formal_MA_datetime, formal_MA_num, lastday):
  76.         R_MA_datetime = formal_MA_datetime
  77.         R_MA_num = formal_MA_num
  78.         if lastday: # 如果计算月最后一天,则直接把月份替换,天数为月份替换后的最后一天
  79.             R_MA_datetime = R_MA_datetime.replace(month=R_MA_num,
  80.                                                   day=calendar.monthrange(R_MA_datetime.year, R_MA_num)[
  81.                                                       1]) # 月份替换,天数为替换月的最后一天
  82.         else:
  83.             if R_MA_datetime.day > \
  84.                     calendar.monthrange(R_MA_datetime.year, R_MA_num)[
  85.                         1]: # 判断当前日期的天数是否大于替换后的月份天数,如果大于,月份在替换后的基础上再加1,天数替换为当前月份天数减替换月份天数
  86.                 R_MA_datetime = R_MA_datetime.replace(month=R_MA_num + 1,
  87.                                                       day=R_MA_datetime.day
  88.                                                           calendar.monthrange(R_MA_datetime.year, R_MA_num)[
  89.                                                               1]) # 月份在替换月的数字上再加1,天数替换为当前月份天数减替换月份天数
  90.             else:
  91.                 R_MA_datetime = R_MA_datetime.replace(month=R_MA_num) # 获取替换月份,day不变
  92.         return R_MA_datetime
  93.     # 月计算的入口函数
  94.     def R_Month_Colculation(self, R_ColStr, lastday, time_truct):
  95.         R_ret_tuple = None
  96.         if R_ColStr.find(“-“) != 1: # 判断是否存在字符串
  97.             col_num = R_ColStr.split(“-“)[1].strip() # 获取需要计算的数字
  98.             if col_num.strip().isdigit(): # 判断获取的数字是否为正整数
  99.                 R_ret_tuple = self.__R_MonthAdd(int(col_num.strip()), “minus”, lastday, time_truct) # 获取tuple time时间格式
  100.             else: # 如果获取的数字不为正整数,则退出程序
  101.                 print(“Please enter right format symbol!!”)
  102.                 print(“If you don’t kown what values is avalable,please use -h to get help!”)
  103.                 exit(4)
  104.         elif R_ColStr.find(“+”) != 1: # 判断+是否存在字符串
  105.             col_num = R_ColStr.split(“+”)[1].strip() # 获取需要计算的数字
  106.             if col_num.strip().isdigit(): # 判断获取的数字是否为正整数
  107.                 R_ret_tuple = self.__R_MonthAdd(int(col_num.strip()), “add”, lastday, time_truct) # 获取tuple time时间格式
  108.             else:
  109.                 print(“Please enter right format symbol!!”)
  110.                 print(“If you don’t kown what values is avalable,please use -h to get help!”)
  111.                 exit(4)
  112.         return R_ret_tuple
  113.     # 天计算的实现函数
  114.     def R_Day_Colculation(self, R_ColStr, time_truct):
  115.         R_ret_tuple = None
  116.         if time_truct == None: # 判断是否指定了输入时间,没指定则获取当前时间,否则使用指定的输入时间
  117.             R_Datatime = datetime.datetime.now()
  118.         else:
  119.             R_Datatime = datetime.datetime.fromtimestamp(time.mktime(time_truct))
  120.         if R_ColStr.find(“-“) != 1: # 判断是否存在字符串
  121.             col_num = R_ColStr.split(“-“)[1].strip() # 获取需要计算的数字
  122.             if col_num.strip().isdigit(): # 判断获取的数字是否为正整数
  123.                 R_ret_tuple = (R_Datatime + datetime.timedelta(
  124.                     int(col_num.strip()))).timetuple() # 获取tuple time时间格式
  125.             else: # 如果获取的数字不为正整数,则退出程序
  126.                 print(“Please enter right format symbol!!”)
  127.                 print(“If you don’t kown what values is avalable,please use -h to get help!”)
  128.                 exit(4)
  129.         elif R_ColStr.find(“+”) != 1: # 判断+是否存在字符串
  130.             col_num = R_ColStr.split(“+”)[1].strip() # 获取需要计算的数字
  131.             if col_num.strip().isdigit(): # 判断获取的数字是否为正整数
  132.                 R_ret_tuple = (R_Datatime + datetime.timedelta(
  133.                     int(col_num.strip()))).timetuple() # 获取tuple time时间格式
  134.             else:
  135.                 print(“Please enter right format symbol!!”)
  136.                 print(“If you don’t kown what values is avalable,please use -h to get help!”)
  137.                 exit(4)
  138.         return R_ret_tuple
  139.     # 周计算的实现函数
  140.     def R_Week_Colculation(self, R_ColStr, time_truct):
  141.         R_ret_tuple = None
  142.         if time_truct == None: # 判断是否指定了输入时间,没指定则获取当前时间,否则使用指定的输入时间
  143.             R_Datatime = datetime.datetime.now()
  144.         else:
  145.             R_Datatime = datetime.datetime.fromtimestamp(time.mktime(time_truct))
  146.         if R_ColStr.find(“-“) != 1: # 判断是否存在字符串
  147.             col_num = R_ColStr.split(“-“)[1].strip() # 获取需要计算的数字
  148.             if col_num.strip().isdigit(): # 判断获取的数字是否为正整数
  149.                 R_ret_tuple = (R_Datatime + datetime.timedelta(
  150.                     weeks=int(col_num.strip()))).timetuple() # 获取tuple time时间格式
  151.             else: # 如果获取的数字不为正整数,则退出程序
  152.                 print(“Please enter right format symbol!!”)
  153.                 print(“If you don’t kown what values is avalable,please use -h to get help!”)
  154.                 exit(4)
  155.         elif R_ColStr.find(“+”) != 1: # 判断+是否存在字符串
  156.             col_num = R_ColStr.split(“+”)[1].strip() # 获取需要计算的数字
  157.             if col_num.strip().isdigit(): # 判断获取的数字是否为正整数
  158.                 R_ret_tuple = (R_Datatime + datetime.timedelta(
  159.                     weeks=int(col_num.strip()))).timetuple() # 获取tuple time时间格式
  160.             else:
  161.                 print(“Please enter right format symbol!!”)
  162.                 print(“If you don’t kown what values is avalable,please use -h to get help!”)
  163.                 exit(4)
  164.         return R_ret_tuple
  165.     # 年计算的实现函数
  166.     def R_Year_Colculation(self, R_ColStr, time_truct):
  167.         R_ret_tuple = None
  168.         if time_truct == None: # 判断是否指定了输入时间,没指定则获取当前时间,否则使用指定的输入时间
  169.             R_Y_Datatime = datetime.datetime.now()
  170.         else:
  171.             R_Y_Datatime = datetime.datetime.fromtimestamp(time.mktime(time_truct))
  172.         if R_ColStr.find(“-“) != 1: # 判断是否存在字符串
  173.             col_num = R_ColStr.split(“-“)[1].strip() # 获取需要计算的数字
  174.             if col_num.strip().isdigit(): # 判断获取的数字是否为正整数
  175.                 # 判断当前时间是否为闰年并且为二月29日,如果是相加/减后不为闰年则在月份加1,日期加1
  176.                 if calendar.isleap(
  177.                         R_Y_Datatime.year) and R_Y_Datatime.month == 2 and R_Y_Datatime.day == 29 and calendar.isleap(
  178.                         R_Y_Datatime.year int(col_num.strip())) == False:
  179.                     R_ret_tuple = (
  180.                     R_Y_Datatime.replace(year=R_Y_Datatime.year int(col_num.strip()), month=R_Y_Datatime.month + 1,
  181.                                          day=1)).timetuple() # 获取tuple time时间格式
  182.                 else:
  183.                     R_ret_tuple = (
  184.                         R_Y_Datatime.replace(
  185.                             year=R_Y_Datatime.year int(col_num.strip()))).timetuple() # 获取tuple time时间格式
  186.             else: # 如果获取的数字不为正整数,则退出程序
  187.                 print(“Please enter right format symbol!!”)
  188.                 print(“If you don’t kown what values is avalable,please use -h to get help!”)
  189.                 exit(4)
  190.         elif R_ColStr.find(“+”) != 1: # 判断+是否存在字符串
  191.             col_num = R_ColStr.split(“+”)[1].strip() # 获取需要计算的数字
  192.             if col_num.strip().isdigit(): # 判断获取的数字是否为正整数
  193.                 # 判断当前时间是否为闰年并且为二月29日,如果是相加/减后不为闰年则在月份加1,日期加1
  194.                 if calendar.isleap(
  195.                         R_Y_Datatime.year) and R_Y_Datatime.month == 2 and R_Y_Datatime.day == 29 and calendar.isleap(
  196.                     R_Y_Datatime.year + col_num.strip()) == False:
  197.                     R_ret_tuple = (
  198.                         R_Y_Datatime.replace(year=R_Y_Datatime.year int(col_num.strip()),
  199.                                              month=R_Y_Datatime.month + 1, day=1)).timetuple() # 获取tuple time时间格式
  200.                 else:
  201.                     R_ret_tuple = (
  202.                         R_Y_Datatime.replace(
  203.                             year=R_Y_Datatime.year + int(col_num.strip()))).timetuple() # 获取tuple time时间格式
  204.             else:
  205.                 print(“Please enter right format symbol!!”)
  206.                 print(“If you don’t kown what values is avalable,please use -h to get help!”)
  207.                 exit(4)
  208.         return R_ret_tuple
  209.     # 获取月的最后一天
  210.     def R_Month_lastday(self, time_tuple):
  211.         R_MA_datetime = datetime.datetime.fromtimestamp(time.mktime(time_tuple)) # time_tuple
  212.         R_MA_datetime = R_MA_datetime.replace(day=(calendar.monthrange(R_MA_datetime.year, R_MA_datetime.month)[1]))
  213.         return R_MA_datetime.timetuple()
  214.     def R_colculation(self):
  215.         ret_tupletime = None
  216.         ColStr = self.rdate[“colculation_string”]
  217.         lastday = self.rdate[“last_day”]
  218.         input_time = None
  219.         if ColStr != None:
  220.             if type(ColStr) != str:
  221.                 print(“Please enter right format symbol!!”)
  222.                 print(“If you don’t kown what values is avalable,please use -h to get help!”)
  223.                 exit(3)
  224.             if (ColStr.find(“-“) != 1) and (ColStr.find(“+”) != 1):
  225.                 print(“Please enter right format symbol!!”)
  226.                 print(“If you don’t kown what values is avalable,please use -h to get help!”)
  227.                 exit(3)
  228.         if self.rdate[“input_time”] != None:
  229.             if self.rdate[“input_format”] == None:
  230.                 i = 1
  231.                 while 1:
  232.                     try:
  233.                         if i < 2:
  234.                             input_time = time.strptime(self.rdate[“input_time”], “%Y%m%d”)
  235.                         else:
  236.                             input_time = time.strptime(self.rdate[“input_time”], “%Y-%m-%d”)
  237.                         break
  238.                     except ValueError as e:
  239.                         if i < 2:
  240.                             i+=1
  241.                             continue
  242.                         print(“The input time and format do not match.”)
  243.                         exit(98)
  244.             elif self.rdate[“input_format”] == “%s”:
  245.                 if self.rdate[“input_time”].isdigit():
  246.                     input_time = time.localtime(int(self.rdate[“input_time”]))
  247.                 else:
  248.                     print(“The input time must be number.”)
  249.                     exit(97)
  250.             else:
  251.                 try:
  252.                     input_time = time.strptime(self.rdate[“input_time”], self.rdate[“input_format”])
  253.                 except ValueError as e:
  254.                     print(“The input time and format do not match.”)
  255.                     exit(98)
  256.         if lastday:
  257.             if ColStr == None:
  258.                 if input_time != None:
  259.                     ret_tupletime = self.R_Month_lastday(input_time)
  260.                 else:
  261.                     ret_tupletime = self.R_Month_lastday(time.localtime())
  262.             # day的计算
  263.             elif ColStr.strip().lower().find(“day”) != 1: # 判断是否传入的字符串中是否存在day关键字
  264.                 ret_tupletime = self.R_Month_lastday(self.R_Day_Colculation(ColStr.strip().lower(), input_time))
  265.             # month的计算
  266.             elif ColStr.strip().lower().find(“month”) != 1: # 判断是否传入的字符串中是否存在day关键字
  267.                 ret_tupletime = self.R_Month_lastday(self.R_Month_Colculation(ColStr.strip().lower(), lastday, input_time))
  268.             # week的计算
  269.             elif ColStr.strip().lower().find(“week”) != 1: # 判断是否传入的字符串中是否存在day关键字
  270.                 ret_tupletime = self.R_Month_lastday(self.R_Week_Colculation(ColStr.strip().lower(), input_time))
  271.             # year的计算
  272.             elif ColStr.strip().lower().find(“year”) != 1: # 判断是否传入的字符串中是否存在day关键字
  273.                 ret_tupletime = self.R_Month_lastday(self.R_Year_Colculation(ColStr.strip().lower(), input_time))
  274.             else:
  275.                 print(“Please enter right format symbol of -c.”)
  276.                 print(“If you don’t kown what values is avalable,please use -h to get help!”)
  277.                 exit(3)
  278.         else:
  279.             if ColStr == None:
  280.                 if self.rdate[“input_time”] != None:
  281.                     ret_tupletime = input_time
  282.                 else:
  283.                     ret_tupletime = time.localtime()
  284.             # day的计算
  285.             elif ColStr.strip().lower().find(“day”) != 1: # 判断是否传入的字符串中是否存在day关键字
  286.                 ret_tupletime = self.R_Day_Colculation(ColStr.strip().lower(), input_time)
  287.             # month的计算
  288.             elif ColStr.strip().lower().find(“month”) != 1: # 判断是否传入的字符串中是否存在day关键字
  289.                 ret_tupletime = self.R_Month_Colculation(ColStr.strip().lower(), lastday, input_time)
  290.             # week的计算
  291.             elif ColStr.strip().lower().find(“week”) != 1: # 判断是否传入的字符串中是否存在day关键字
  292.                 ret_tupletime = self.R_Week_Colculation(ColStr.strip().lower(), input_time)
  293.             # year的计算
  294.             elif ColStr.strip().lower().find(“year”) != 1: # 判断是否传入的字符串中是否存在day关键字
  295.                 ret_tupletime = self.R_Year_Colculation(ColStr.strip().lower(), input_time)
  296.             else:
  297.                 print(“Please enter right format symbol of -c.”)
  298.                 print(“If you don’t kown what values is avalable,please use -h to get help!”)
  299.                 exit(3)
  300.         return ret_tupletime
  301. def func_help():
  302.     print(“”
  303.     NAME:
  304.         rdate –display date and time
  305.     SYNOPSIS:
  306.         rdate [-f] [time format] [-c] [colculation format] [-d] [input_time] [input_time_format]
  307.     DESCRIPTION:
  308.         -c: value is day/week/month/year,plus +/-,plus a number which is number to colculate
  309.         -l: obtain a number which is last day of month
  310.         -d:
  311.             input_time: enter a time string
  312.             input_time_format: enter a time format for input time,default %Y%m%d or %Y-%m-%d
  313.         -f:
  314.          %A is replaced by national representation of the full weekday name.
  315.          %a is replaced by national representation of the abbreviated weekday name.
  316.          %B is replaced by national representation of the full month name.
  317.          %b is replaced by national representation of the abbreviated month name.
  318.          %C is replaced by (year / 100) as decimal number; single digits are preceded by a zero.
  319.          %c is replaced by national representation of time and date.
  320.          %D is equivalent to “%m/%d/%y”.
  321.          %d is replaced by the day of the month as a decimal number (01-31).
  322.          %E* %O*
  323.                 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
  324.                 representations.
  325.                 Additionally %OB implemented to represent alternative months names (used standalone, without day mentioned).
  326.          %e is replaced by the day of the month as a decimal number (1-31); single digits are preceded by a blank.
  327.          %F is equivalent to “%Y-%m-%d”.
  328.          %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
  329.                 the week).
  330.          %g is replaced by the same year as in “%G”, but as a decimal number without century (00-99).
  331.          %H is replaced by the hour (24-hour clock) as a decimal number (00-23).
  332.          %h the same as %b.
  333.          %I is replaced by the hour (12-hour clock) as a decimal number (01-12).
  334.          %j is replaced by the day of the year as a decimal number (001-366).
  335.          %k is replaced by the hour (24-hour clock) as a decimal number (0-23); single digits are preceded by a blank.
  336.          %l is replaced by the hour (12-hour clock) as a decimal number (1-12); single digits are preceded by a blank.
  337.          %M is replaced by the minute as a decimal number (00-59).
  338.          %m is replaced by the month as a decimal number (01-12).
  339.          %n is replaced by a newline.
  340.          %O* the same as %E*.
  341.          %p is replaced by national representation of either ante meridiem (a.m.) or post meridiem (p.m.) as appropriate.
  342.          %R is equivalent to “%H:%M”.
  343.          %r is equivalent to “%I:%M:%S %p”.
  344.          %S is replaced by the second as a decimal number (00-60).
  345.          %s is replaced by the number of seconds since the Epoch, UTC (see mktime(3)).
  346.          %T is equivalent to “%H:%M:%S”.
  347.          %t is replaced by a tab.
  348.          %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number (00-53).
  349.          %u is replaced by the weekday (Monday as the first day of the week) as a decimal number (1-7).
  350.          %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
  351.                 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.
  352.          %v is equivalent to “%e-%b-%Y”.
  353.          %W is replaced by the week number of the year (Monday as the first day of the week) as a decimal number (00-53).
  354.          %w is replaced by the weekday (Sunday as the first day of the week) as a decimal number (0-6).
  355.          %X is replaced by national representation of the time.
  356.          %x is replaced by national representation of the date.
  357.          %Y is replaced by the year with century as a decimal number.
  358.          %y is replaced by the year without century as a decimal number (00-99).
  359.          %Z is replaced by the time zone name.
  360.          %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
  361.                 two digits each and no delimiter between them (common form for RFC 822 date headers).
  362.          %+ is replaced by national representation of the date and time (the format is similar to that produced by date(1)).
  363.          %-* GNU libc extension. Do not do any padding when performing numerical outputs.
  364.          %_* GNU libc extension. Explicitly specify space for padding.
  365.          %0* GNU libc extension. Explicitly specify zero for padding.
  366.          %% is replaced by `%’.
  367.     EXAMPLE:
  368.          rdate –2017-10-23 11:04:51 Monday
  369.          rdate -f “%Y%m_%d” –2017-10-23
  370.          rdate -f “%Y%m_%d” -c “day3” –2017-10-20
  371.          rdate -f “%Y%m_%d” -c “day+3” –2017-10-26
  372.          rdate -f “%Y%m_%d” -c “month+3” –2017-7-23
  373.          rdate -f “%Y%m_%d” -c “year+3” –2020-7-23
  374.          rdate -c “week 1” -f “%Y%m%d %V” –2018-02-15 07
  375.          rdate -c “day 30” -f “%Y%m%d” -l –2018-01-31
  376.          rdate -d “19720131” “%Y%m%d” –1972-01-31 00:00:00 Monday
  377.     ““”)
  378. if __name__ == “__main__”:
  379.     d1 = DateColculation()
  380.     if len(sys.argv) > 1:
  381.         i = 1
  382.         while i < len(sys.argv):
  383.             if sys.argv[i] == “-h”: # 判断输入的参数是否为h,既获取帮助
  384.                 func_help()
  385.                 exit(0)
  386.             elif sys.argv[i] == “-f”: # f表示format,表示指定的输出时间格式
  387.                 i = i + 1
  388.                 if i >= len(sys.argv): # 判断f的值的下标是否大于等于参数个数,如果为真则表示没有指定f的值
  389.                     print(“The value of -f must be specified!!!”)
  390.                     exit(1)
  391.                 elif sys.argv[i] == “-c”:
  392.                     print(“The value of -f must be specified!!!”)
  393.                     exit(1)
  394.                 elif re.match(“^-“, sys.argv[i]) != None: # 判断f的值,如果f的下个参数以开头,表示没有指定f值
  395.                     print(“The value of -f must be specified!!!”)
  396.                     exit(1)
  397.                 d1.rdate[“time_format”] = sys.argv[i] # 获取输出时间格式
  398.             elif sys.argv[i] == “-c”: # c表示colculation,计算
  399.                 i = i + 1
  400.                 if i >= len(sys.argv): # 判断f的值的下标是否大于等于参数个数,如果为真则表示没有指定f的值
  401.                     print(“The value of -c must be specified!!!”)
  402.                     exit(2)
  403.                 elif sys.argv[i] == “-f”:
  404.                     print(“The value of -c must be specified!!!”)
  405.                     exit(2)
  406.                 elif (re.match(“^-“, sys.argv[i]) != None): # 判断f的值,如果f的下个参数以开头,表示没有指定f值
  407.                     print(“The value of -c must be specified!!!”)
  408.                     exit(2)
  409.                 d1.rdate[“colculation_string”] = sys.argv[i] # 获取需要计算的字符串参数内容
  410.             elif sys.argv[i] == “-d”: # d date 表示指定输入的时间和输入的时间格式
  411.                 i += 1
  412.                 if i >= len(sys.argv): # 判断d的值的下标是否大于等于参数个数,如果为真则表示没有指定的值
  413.                     print(“The value of -d must be specified!!!”)
  414.                     exit(3)
  415.                 elif (re.match(“^-“, sys.argv[i]) != None): # 判断d的值,如果df的下个参数以开头,表示没有指定df值
  416.                     print(“The value of -c must be specified!!!”)
  417.                     exit(3)
  418.                 d1.rdate[“input_time”] = sys.argv[i]
  419.                 if (i+1 < len(sys.argv) and re.match(“^-“, sys.argv[(i+1)]) == None):
  420.                     d1.rdate[“input_format”] = sys.argv[i+1]
  421.                     i+=1
  422.             elif sys.argv[i] == “-l”: # l表示获取月份的最后一天
  423.                 d1.rdate[“last_day”] = True
  424.             else:
  425.                 print(“You must enter right parametr.”)
  426.                 print(“If you don’t kown what values is avalable,please use -h to get help!”)
  427.                 exit(3)
  428.             i = i + 1
  429.         d1.rdate[“time_tuple”] = d1.R_colculation() # 获取时间的元组,通过R_colculation函数,R_colculation参数为传入一个需要计算的时间字符串
  430.         print(time.strftime(d1.rdate[“time_format”], d1.rdate[“time_tuple”]))
  431.         exit(0)
  432.     else: # 如果不输入参数,则输出默认格式化的本地时间
  433.         print(time.strftime(d1.rdate[“time_format”], d1.rdate[“time_tuple”]))
  434.         exit(0)


    原文作者:raysuen
    原文地址: http://blog.itpub.net/28572479/viewspace-2150704/
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞