现在的位置: 首页 > 综合 > 正文

Python实践——datetime日期操作脚本

2019年08月04日 ⁄ 综合 ⁄ 共 7483字 ⁄ 字号 评论关闭
  1. #!/usr/bin/python   
  2. # -*- coding: utf-8 -*-   
  3. #countDays.py   
  4. # version 0.10      edited by lingyue.wkl 20110819 11:00:00   
  5. # version 0.11      modified by lingyue.wkl 20110820 11:37:00   add functions for days list   
  6. #this script count days,between two date or one date and the days between them   
  7.   
  8. #考虑下,很多方法可以抽象出来,进一步优化,先期先实现功能吧   
  9. #下一个版本  改进所有函数,优化之,抽象之   
  10.   
  11.   
  12. import time,getopt,sys,datetime  
  13.   
  14. def date_to_str(in_date):  
  15.     return str(in_date)[:10]  
  16. #计算两个日期之间相隔天数   
  17. def get_count_between_two_date(begin_date,end_date):  
  18.   b_date = begin_date.split("-")  
  19.   b_date = [int(num) for num in b_date]  
  20.   b_date_time = datetime.datetime(b_date[0],b_date[1],b_date[2])  
  21.   
  22.   e_date = end_date.split("-")  
  23.   e_date = [int(num) for num in e_date]  
  24.   e_date_time = datetime.datetime(e_date[0],e_date[1],e_date[2])  
  25.   
  26.   return (e_date_time - b_date_time).days  
  27.   
  28. #计算某个日期前n天是哪一天   默认日期是今天   
  29. def get_n_days_before_or_after_oneday(n_days,in_date=str(datetime.date.today())[:10]):  
  30.   begin_date = in_date.split("-")  
  31.   begin_date = [int(num) for num in begin_date]  
  32.   return str(datetime.datetime(begin_date[0],begin_date[1],begin_date[2]) + datetime.timedelta(days=n_days))[:10]  
  33.   
  34.   
  35. def get_year():  
  36.     return str(datetime.date.today())[:4]  
  37.   
  38. def get_month():  
  39.     return str(datetime.date.today())[5:7]  
  40.   
  41. def get_day():  
  42.     return str(datetime.date.today())[8:]  
  43.   
  44. def get_now():  
  45.     return datetime.datetime.now()  
  46.   
  47. def get_today():  
  48.     return datetime.date.today()  
  49.   
  50. def get_yesterday():  
  51.   return get_n_days_before_or_after_oneday(-1,str(datetime.date.today())[:10])  
  52.   
  53. def get_tomorrow():  
  54.   return get_n_days_before_or_after_oneday(1,str(datetime.date.today())[:10])  
  55.   
  56. #两个日期之间  n天的日期列表   
  57.   
  58. def get_n_daystimes_list_of_two_date(begin_date,end_date):  
  59.   b_date = begin_date.split("-")  
  60.   b_date = [int(num) for num in b_date]  
  61.   b_date_time = datetime.datetime(b_date[0],b_date[1],b_date[2])  
  62.   
  63.   e_date = end_date.split("-")  
  64.   e_date = [int(num) for num in e_date]  
  65.   e_date_time = datetime.datetime(e_date[0],e_date[1],e_date[2])  
  66.   
  67.   days = (e_date_time - b_date_time).days  
  68.   n_days_list = []  
  69.   for i in range(0,days+1):  
  70.     n_days_list.append(str(b_date_time + datetime.timedelta(days=i)))  
  71.   return n_days_list  
  72.   
  73. def get_n_days_list_of_two_date(begin_date,end_date):  
  74.   return [str(day)[:10for day in get_n_daystimes_list_of_two_date(begin_date,end_date)]  
  75.   
  76. def get_n_dayswiththreetimes_list_of_two_date(begin_date,end_date):  
  77.   days =  get_n_days_list_of_two_date(begin_date,end_date)  
  78.   days_three_time_list = []  
  79.   for day in days:  
  80.     for i in range(0,3):  
  81.         if i == 0:  
  82.            days_three_time_list.append(day+" 00:00:00")  
  83.         elif i == 1:  
  84.            days_three_time_list.append(day+" 12:00:00")  
  85.         else:  
  86.            days_three_time_list.append(day+" 23:59:59")  
  87.   return days_three_time_list  
  88.   
  89. #某个日期之前n天  所有日期列表   
  90.   
  91. def get_n_daystimes_list_before_or_after_one_day(n_days,end_date=str(datetime.date.today())[:10]):  
  92.   begin_date = get_n_days_before_or_after_oneday(n_days,end_date)  
  93.   return get_n_daystimes_list_of_two_date(begin_date,end_date)  
  94.   
  95. def get_n_days_list_before_or_after_one_day(n_days,end_date=str(datetime.date.today())[:10]):  
  96.   begin_date = get_n_days_before_or_after_oneday(n_days,end_date)  
  97.   return get_n_days_list_of_two_date(begin_date,end_date)  
  98.   
  99. def get_n_dayswiththreetimes_list_before_or_after_one_day(n_days,end_date=str(datetime.date.today())[:10]):  
  100.   begin_date = get_n_days_before_or_after_oneday(n_days,end_date)  
  101.   return get_n_dayswiththreetimes_list_of_two_date(begin_date,end_date)  
  102.   
  103. def help_msg():  
  104.   print("功能:日期相关操作")  
  105.   print("选项:")  
  106.   print("\t 默认,无选项,输出当天日期,格式2011-08-20")  
  107.   print("\t -y   [可选,输出当前年份]")  
  108.   print("\t -m   [可选,输出当前月份]")  
  109.   print("\t -d   [可选,输出当前日]")  
  110.   print("\t -n +-数字  [可选,计算当前日期前后多少天的日期,数字为负表示往前]")  
  111.   print("\t -f 2011-10-22[可选,指定坐标日期,即以指定日期开始计算,若不指定,坐标日期为当天]")  
  112.   print("\t -t 2011-10-25  [可选,目标日期,可用于计算两个日期相隔天数]")  
  113.   print("\t -l [1|2|3]  [可选,是否列表,若选定,输出日期间的所有序列,1 2 3 代表三种不同格式]")  
  114.   sys.exit(0)  
  115.   
  116. def print_list(l):  
  117.   for i in l:  
  118.     print(i)  
  119. #print(get_year())   
  120. #print(get_month())   
  121. #print(get_day())   
  122. #print(get_now())   
  123. #print(get_today())   
  124. #print(get_yesterday())   
  125. #print(get_tomorrow())   
  126. #print(get_n_days_before_or_after_oneday(2,"2011-08-20"))   
  127. #print(get_n_daystimes_list_of_two_date("2011-08-01","2011-08-05"))   
  128. #print(get_n_days_list_of_two_date("2011-08-01","2011-08-05"))   
  129. #print(get_n_dayswiththreetimes_list_of_two_date("2011-08-01","2011-08-05"))    
  130. #print(get_n_daystimes_list_before_or_after_ond_day(-5,"2011-08-20"))   
  131. #print(get_n_days_list_before_or_after_ond_day(-5,"2011-08-20"))   
  132. #print(get_n_dayswiththreetimes_list_before_or_after_ond_day(-5,"2011-08-20"))   
  133.   
  134. #程序入口,读入参数,执行   
  135. def main():  
  136.     is_list = False  
  137.     try:  
  138.         opts,args = getopt.getopt(sys.argv[1:],"n:f:t:o:ymdhrl:")  
  139.           
  140.         if len(opts) == 0:  
  141.           print(get_today())  
  142.           sys.exit(0)  
  143.   
  144.         for op,value in opts:  
  145.           if op in ("-h","-H","--help"):  
  146.             help_msg()  
  147.           if op == "-y":  
  148.             print(get_year())  
  149.             sys.exit(0)  
  150.           elif op == "-m":  
  151.             print(get_month())  
  152.             sys.exit(0)  
  153.           elif op == "-d":  
  154.             print(get_day())  
  155.             sys.exit(0)  
  156.           elif op == "-n":  
  157.             n_days = int(value)  
  158.           elif op == "-f":  
  159.             from_date = value  
  160.           elif op == "-t":  
  161.             to_date = value  
  162.           elif op == "-l":  
  163.             is_list = True  
  164.             list_type = value  
  165.   
  166.     except getopt.GetoptError:  
  167.       print(sys.argv[0]+" : params are not defined well!")  
  168.   
  169.     #if "n_days" not in dir() and "from_date" not in dir() and "to_date" not in dir():   
  170.     #     print(result_str)   
  171.      
  172.     if "n_days" in dir() and "from_date" not in dir() and "to_date" not in dir():  
  173.       if not is_list:  
  174.          print(get_n_days_before_or_after_today(n_days))  
  175.       else:  
  176.          if list_type == "1":  
  177.            result_list = get_n_days_list_before_or_after_one_day(n_days)  
  178.          elif list_type == "2":  
  179.            result_list = get_n_daystimes_list_before_or_after_one_day(n_days)  
  180.          elif list_type == "3":  
  181.            result_list = get_n_dayswiththreetimes_list_before_or_after_one_day(n_days)  
  182.          print_list(result_list)  
  183.      
  184.     if "n_days" in dir() and "from_date" in dir() and "to_date" not in dir():  
  185.       if not is_list:  
  186.          print(get_n_days_before_or_after_oneday(n_days,from_date))  
  187.       else:  
  188.          if list_type == "1":  
  189.            result_list = get_n_days_list_before_or_after_one_day(n_days,from_date)  
  190.          elif list_type == "2":  
  191.            result_list = get_n_daystimes_list_before_or_after_one_day(n_days,from_date)  
  192.          elif list_type == "3":  
  193.            result_list = get_n_dayswiththreetimes_list_before_or_after_one_day(n_days,from_date)  
  194.          print_list(result_list)  
  195.   
  196.   
  197.     if "n_days" not in dir() and "from_date" in dir() and "to_date" in dir():  
  198.       if not is_list:  
  199.          print(get_count_between_two_date(from_date,to_date))  
  200.       else:  
  201.          if list_type == "1":  
  202.            result_list = get_n_days_list_of_two_date(from_date,to_date)  
  203.          elif list_type == "2":  
  204.            result_list = get_n_daystimes_list_of_two_date(from_date,to_date)  
  205.          elif list_type == "3":  
  206.            result_list = get_n_dayswiththreetimes_list_of_two_date(from_date,to_date)  
  207.          print_list(result_list)  
  208.         
  209.         
  210.   
  211. main()  

抱歉!评论已关闭.