iis服务器助手广告广告
返回顶部
首页 > 资讯 > 操作系统 >python实现时间的加减,类似linux的date命令
  • 920
分享到

python实现时间的加减,类似linux的date命令

2023-06-02 12:06:09 920人浏览 安东尼
摘要

内容如题原因:solaris等os不能做时间的运算处理,个人爱好。之前用c实现了一版,这里再次用python实现一版,后期应该还有改进版改进:1 代码优化       &

内容如题
原因: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.

脚本下载地址:https://GitHub.com/raysuen/rdate

#!/usr/bin/env python# _*_coding:utf-8_*_# Auth by raysuen# version v8.0import datetimeimport timeimport calendarimport sysimport 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_tupletimedef 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)




--结束END--

本文标题: python实现时间的加减,类似linux的date命令

本文链接: https://www.lsjlt.com/news/230069.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python实现时间的加减,类似linux的date命令
    内容如题原因:solaris等os不能做时间的运算处理,个人爱好。之前用c实现了一版,这里再次用python实现一版,后期应该还有改进版改进:1 代码优化       &...
    99+
    2023-06-02
  • python 实现类似sed命令的文件内
    #!/usr/bin/env python     #_*_coding:utf-8 _*_     #replace()方法把字符串中的 old(旧字符串)替换成new(新字符串),如果指定第三个参数max,则替换不超过 max 次。  ...
    99+
    2023-01-31
    命令 类似 文件
  • Shell时间date相关的命令介绍
    这篇文章主要讲解了“Shell时间date相关的命令介绍”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Shell时间date相关的命令介绍”吧!date +%Fdate ...
    99+
    2023-06-09
  • Linux中date命令的参数及获时间戳的方法
    这篇文章主要讲解了“Linux中date命令的参数及获时间戳的方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Linux中date命令的参数及获时间戳的方法”吧!1.时间命令:date向d...
    99+
    2023-06-13
  • Linux系统中的date时间日期命令的使用教程
    本篇内容主要讲解“Linux系统中的date时间日期命令的使用教程”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Linux系统中的date时间日期命令的使用教程”吧!“date”命令使用标准的输...
    99+
    2023-06-12
  • windows下的类似linux下的grep命令--findstr
    Windows下的类似linux下的grep命令——findstr 经常用linux下的greTCP 0.0.0.0:1521 0.0.0.0:0 LISTENING TCP 192.168.1....
    99+
    2023-05-26
    findstr命令 linux findstr 命令 grep
  • 用date命令修改Linux系统的时间为什么无效
    这篇文章主要讲解了“用date命令修改Linux系统的时间为什么无效”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“用date命令修改Linux系统的时间为什么无效”吧!需要手动修改一下系统的...
    99+
    2023-06-13
  • python时间序列数据相减的实现
    目录1.将读取的时间序列数据转化为timestamp格式2.时间数据的相减在此记录自己学习python数据分析过程中学到的一些数据处理的小技巧。本节主要分享时间数据的相减。 1.将读...
    99+
    2023-05-18
    python时间序列相减 python时间相减
  • python中时间的加n和减n运算
       好多朋友都遇到过python推算时间的问题,有些把时间转换成整数做推算,这样遇到特殊的时间和日期就会出现错误,在python中时间的推算很简单,主要就是用到datetime.timedelta方法,进行时间的加n减n运算:>&...
    99+
    2023-01-31
    时间 python
  • Linux系统中date命令的使用实例
    本篇内容主要讲解“Linux系统中date命令的使用实例”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Linux系统中date命令的使用实例”吧!date用法1:  &nbs...
    99+
    2023-06-12
  • 基于Go语言实现类似tree命令的小程序
    目录需求目的需求分析需求 写一个简版类似于unix tree命令的go语言小程序,如下参数仿照于tree命令的文档 该小程序支持的功能如下: mtree命令默认打印以层级结构打印所有...
    99+
    2024-04-02
  • 怎么用PHP类来实现两个数间的加减乘除
    本篇内容主要讲解“怎么用PHP类来实现两个数间的加减乘除”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么用PHP类来实现两个数间的加减乘除”吧!首先打开PHP编辑器,创建一个PHP示例文件;上...
    99+
    2023-06-20
  • python 基于空间相似度的K-means轨迹聚类的实现
    这里分享一些轨迹聚类的基本方法,涉及轨迹距离的定义、kmeans聚类应用。 需要使用的python库如下 import pandas as pd import numpy as ...
    99+
    2024-04-02
  • python实现类似awk的简单功能
    命令行的awk很方便,但处理灵活一点的话对awk不熟,深入学习又没太大必要,用python做个简单的,复杂的话也用python脚本实现,程序的一致性更好。 #!/usr/bin/python #coding:utf-8 import ...
    99+
    2023-01-31
    类似 简单 功能
  • Linux下时间设置的相关命令整理
    这篇文章主要介绍“Linux下时间设置的相关命令整理”,在日常操作中,相信很多人在Linux下时间设置的相关命令整理问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Linux下时间设置的相关命令整理”的疑惑有所...
    99+
    2023-06-12
  • Linux系统同步时间的命令是什么
    本篇文章为大家展示了Linux系统同步时间的命令是什么,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。当我们在Linux系统中搭建集群时特别是分布式系统,时间是非常重要的因素,,例如HBASE的时候,...
    99+
    2023-06-28
  • JavaScript实现类似Express的中间件系统(实例详解)
    目录Express 的中间件系统实现代码如何实现异步执行链如何将控制权交给中间件函数使用示例应用级中间件与路由级中间件Express 的中间件系统 在 Express 中可以给一个请...
    99+
    2023-02-14
    js Express的中间件系统 Express的中间件
  • linux中怎么利用ntp命令实现时间同步功能
    这篇文章给大家介绍linux中怎么利用ntp命令实现时间同步功能,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。如果服务器的时间出现混乱,将导致很多意想不到的问题。使用NTP,可以使服务器获取正确的时间,从而避免出现问题...
    99+
    2023-06-13
  • python如何实现类似defer的延迟调用
    这篇文章给大家分享的是有关python如何实现类似defer的延迟调用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。实现类似 defer 的延迟调用在 Golang 中有一种延迟调用的机制,关键字是 defer,...
    99+
    2023-06-27
  • 怎么限制Linux命令程序运行的时间
    本篇内容主要讲解“怎么限制Linux命令程序运行的时间”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么限制Linux命令程序运行的时间”吧!Linux提供了大量的命令,每个命令都是唯一的,并且...
    99+
    2023-06-15
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作