歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python實踐——datetime日期操作腳本

Python實踐——datetime日期操作腳本

日期:2017/3/1 10:48:59   编辑:Linux編程

Python實踐——datetime日期操作腳本,最近需要做一些日期的操作,寫了一個腳本.

  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. import time,getopt,sys,datetime
  10. def date_to_str(in_date):
  11. return str(in_date)[:10]
  12. #計算兩個日期之間相隔天數
  13. def get_count_between_two_date(begin_date,end_date):
  14. b_date = begin_date.split("-")
  15. b_date = [int(num) for num in b_date]
  16. b_date_time = datetime.datetime(b_date[0],b_date[1],b_date[2])
  17. e_date = end_date.split("-")
  18. e_date = [int(num) for num in e_date]
  19. e_date_time = datetime.datetime(e_date[0],e_date[1],e_date[2])
  20. return (e_date_time - b_date_time).days
  21. #計算某個日期前n天是哪一天 默認日期是今天
  22. def get_n_days_before_or_after_oneday(n_days,in_date=str(datetime.date.today())[:10]):
  23. begin_date = in_date.split("-")
  24. begin_date = [int(num) for num in begin_date]
  25. return str(datetime.datetime(begin_date[0],begin_date[1],begin_date[2]) + datetime.timedelta(days=n_days))[:10]
  26. def get_year():
  27. return str(datetime.date.today())[:4]
  28. def get_month():
  29. return str(datetime.date.today())[5:7]
  30. def get_day():
  31. return str(datetime.date.today())[8:]
  32. def get_now():
  33. return datetime.datetime.now()
  34. def get_today():
  35. return datetime.date.today()
  36. def get_yesterday():
  37. return get_n_days_before_or_after_oneday(-1,str(datetime.date.today())[:10])
  38. def get_tomorrow():
  39. return get_n_days_before_or_after_oneday(1,str(datetime.date.today())[:10])
  40. #兩個日期之間 n天的日期列表
  41. def get_n_daystimes_list_of_two_date(begin_date,end_date):
  42. b_date = begin_date.split("-")
  43. b_date = [int(num) for num in b_date]
  44. b_date_time = datetime.datetime(b_date[0],b_date[1],b_date[2])
  45. e_date = end_date.split("-")
  46. e_date = [int(num) for num in e_date]
  47. e_date_time = datetime.datetime(e_date[0],e_date[1],e_date[2])
  48. days = (e_date_time - b_date_time).days
  49. n_days_list = []
  50. for i in range(0,days+1):
  51. n_days_list.append(str(b_date_time + datetime.timedelta(days=i)))
  52. return n_days_list
  53. def get_n_days_list_of_two_date(begin_date,end_date):
  54. return [str(day)[:10] for day in get_n_daystimes_list_of_two_date(begin_date,end_date)]
  55. def get_n_dayswiththreetimes_list_of_two_date(begin_date,end_date):
  56. days = get_n_days_list_of_two_date(begin_date,end_date)
  57. days_three_time_list = []
  58. for day in days:
  59. for i in range(0,3):
  60. if i == 0:
  61. days_three_time_list.append(day+" 00:00:00")
  62. elif i == 1:
  63. days_three_time_list.append(day+" 12:00:00")
  64. else:
  65. days_three_time_list.append(day+" 23:59:59")
  66. return days_three_time_list
  67. #某個日期之前n天 所有日期列表
  68. def get_n_daystimes_list_before_or_after_one_day(n_days,end_date=str(datetime.date.today())[:10]):
  69. begin_date = get_n_days_before_or_after_oneday(n_days,end_date)
  70. return get_n_daystimes_list_of_two_date(begin_date,end_date)
  71. def get_n_days_list_before_or_after_one_day(n_days,end_date=str(datetime.date.today())[:10]):
  72. begin_date = get_n_days_before_or_after_oneday(n_days,end_date)
  73. return get_n_days_list_of_two_date(begin_date,end_date)
  74. def get_n_dayswiththreetimes_list_before_or_after_one_day(n_days,end_date=str(datetime.date.today())[:10]):
  75. begin_date = get_n_days_before_or_after_oneday(n_days,end_date)
  76. return get_n_dayswiththreetimes_list_of_two_date(begin_date,end_date)
  77. def help_msg():
  78. print("功能:日期相關操作")
  79. print("選項:")
  80. print("\t 默認,無選項,輸出當天日期,格式2011-08-20")
  81. print("\t -y [可選,輸出當前年份]")
  82. print("\t -m [可選,輸出當前月份]")
  83. print("\t -d [可選,輸出當前日]")
  84. print("\t -n +-數字 [可選,計算當前日期前後多少天的日期,數字為負表示往前]")
  85. print("\t -f 2011-10-22[可選,指定坐標日期,即以指定日期開始計算,若不指定,坐標日期為當天]")
  86. print("\t -t 2011-10-25 [可選,目標日期,可用於計算兩個日期相隔天數]")
  87. print("\t -l [1|2|3] [可選,是否列表,若選定,輸出日期間的所有序列,1 2 3 代表三種不同格式]")
  88. sys.exit(0)
  89. def print_list(l):
  90. for i in l:
  91. print(i)
  92. #print(get_year())
  93. #print(get_month())
  94. #print(get_day())
  95. #print(get_now())
  96. #print(get_today())
  97. #print(get_yesterday())
  98. #print(get_tomorrow())
  99. #print(get_n_days_before_or_after_oneday(2,"2011-08-20"))
  100. #print(get_n_daystimes_list_of_two_date("2011-08-01","2011-08-05"))
  101. #print(get_n_days_list_of_two_date("2011-08-01","2011-08-05"))
  102. #print(get_n_dayswiththreetimes_list_of_two_date("2011-08-01","2011-08-05"))
  103. #print(get_n_daystimes_list_before_or_after_ond_day(-5,"2011-08-20"))
  104. #print(get_n_days_list_before_or_after_ond_day(-5,"2011-08-20"))
  105. #print(get_n_dayswiththreetimes_list_before_or_after_ond_day(-5,"2011-08-20"))
  106. #程序入口,讀入參數,執行
  107. def main():
  108. is_list = False
  109. try:
  110. opts,args = getopt.getopt(sys.argv[1:],"n:f:t:o:ymdhrl:")
  111. if len(opts) == 0:
  112. print(get_today())
  113. sys.exit(0)
  114. for op,value in opts:
  115. if op in ("-h","-H","--help"):
  116. help_msg()
  117. if op == "-y":
  118. print(get_year())
  119. sys.exit(0)
  120. elif op == "-m":
  121. print(get_month())
  122. sys.exit(0)
  123. elif op == "-d":
  124. print(get_day())
  125. sys.exit(0)
  126. elif op == "-n":
  127. n_days = int(value)
  128. elif op == "-f":
  129. from_date = value
  130. elif op == "-t":
  131. to_date = value
  132. elif op == "-l":
  133. is_list = True
  134. list_type = value
  135. except getopt.GetoptError:
  136. print(sys.argv[0]+" : params are not defined well!")
  137. #if "n_days" not in dir() and "from_date" not in dir() and "to_date" not in dir():
  138. # print(result_str)
  139. if "n_days" in dir() and "from_date" not in dir() and "to_date" not in dir():
  140. if not is_list:
  141. print(get_n_days_before_or_after_today(n_days))
  142. else:
  143. if list_type == "1":
  144. result_list = get_n_days_list_before_or_after_one_day(n_days)
  145. elif list_type == "2":
  146. result_list = get_n_daystimes_list_before_or_after_one_day(n_days)
  147. elif list_type == "3":
  148. result_list = get_n_dayswiththreetimes_list_before_or_after_one_day(n_days)
  149. print_list(result_list)
  150. if "n_days" in dir() and "from_date" in dir() and "to_date" not in dir():
  151. if not is_list:
  152. print(get_n_days_before_or_after_oneday(n_days,from_date))
  153. else:
  154. if list_type == "1":
  155. result_list = get_n_days_list_before_or_after_one_day(n_days,from_date)
  156. elif list_type == "2":
  157. result_list = get_n_daystimes_list_before_or_after_one_day(n_days,from_date)
  158. elif list_type == "3":
  159. result_list = get_n_dayswiththreetimes_list_before_or_after_one_day(n_days,from_date)
  160. print_list(result_list)
  161. if "n_days" not in dir() and "from_date" in dir() and "to_date" in dir():
  162. if not is_list:
  163. print(get_count_between_two_date(from_date,to_date))
  164. else:
  165. if list_type == "1":
  166. result_list = get_n_days_list_of_two_date(from_date,to_date)
  167. elif list_type == "2":
  168. result_list = get_n_daystimes_list_of_two_date(from_date,to_date)
  169. elif list_type == "3":
  170. result_list = get_n_dayswiththreetimes_list_of_two_date(from_date,to_date)
  171. print_list(result_list)
  172. main()

Copyright © Linux教程網 All Rights Reserved