Python工具類(二)—— 操作時間相關


  1 #!/usr/bin/env python
  2 # -*- coding: utf-8 -*-
  3 """
  4 __title__ = '操作時間的工具類'
  5 
  6 """
  7 import datetime
  8 import time
  9 
 10 
 11 # ==========================
 12 # ========== time ==========
 13 # ==========================
 14 
 15 
 16 def getCurrentMilliSecondTime():
 17     """
 18     description:  獲取當前時間-毫秒級
 19     return:       1557730376981 -> str
 20     """
 21     timestamps = str(round(time.time() * 1000))
 22     return timestamps
 23 
 24 
 25 def getCurrentSecondTime():
 26     """
 27     description:  獲取當前時間-秒級
 28     return:       1557730377 -> str
 29     """
 30     timestamps = str(round(time.time()))
 31     return timestamps
 32 
 33 
 34 def getCurrentTimeTuple(times=time.time()):
 35     """
 36     description:  接受秒級時間戳並返回時間元組(與mktime(tuple)相反)
 37     times:        默認當前時間 可傳second
 38     return:       (tm_year=2019, tm_mon=5, tm_mday=13, tm_hour=10, tm_min=9, tm_sec=18, tm_wday=0, tm_yday=133, tm_isdst=0) -> tuple
 39     tips:         time.localtime() 不傳參則取當前時間
 40     """
 41     timestamps = time.localtime(times)
 42     return timestamps
 43 
 44 
 45 def getTimeByTuple(tupleTime=time.localtime()):
 46     """
 47     description:  接受時間元組並返回秒級時間戳(與localtime(sec)相反)
 48     tupleTime:    默認當前時間的元組 可通過time.localtime() or datetime.datetime.now().timetuple()獲取
 49     return:       1557733061 -> str
 50     """
 51     timestamps = str(round(time.mktime(tupleTime)))
 52     return timestamps
 53 
 54 
 55 def getCurrentFormatTimeStr(times=time.time()):
 56     """
 57     description:  將指定時間元組格式化為字符串
 58     times:        默認當前時間 可傳second
 59     return:       2019-05-13 15:00:47 -> str
 60     tips:         %y 兩位數的年份表示(00-99)    %Y 四位數的年份表示(000-9999)   %m 月份(01-12)    %d 月內中的一天(0-31)
 61                   %H 24小時制小時數(0-23)      %I 12小時制小時數(01-12)        %M 分鍾數(00=59)  %S 秒(00-59)   %w 星期(0-6)
 62     """
 63     timestamps = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(times))
 64     return timestamps
 65 
 66 
 67 def getCurrentTimeTupleByFormatStr(time_str=str(datetime.datetime.now()).split(".")[0], format_type="%Y-%m-%d %H:%M:%S"):
 68     """
 69     description:  接受格式化字符串返回時間元組
 70     time_str:     格式化字符串   如:2019-05-13 15:00:47    默認當前時間
 71     format_type:  格式化規則    如:%Y-%m-%d %H:%M:%S      默認%Y-%m-%d %H:%M:%S
 72     return:       (tm_year=2019, tm_mon=5, tm_mday=13, tm_hour=10, tm_min=9, tm_sec=18, tm_wday=0, tm_yday=133, tm_isdst=0) -> tuple
 73     """
 74     return time.strptime(time_str, format_type)
 75 
 76 
 77 def getCurrentTimeStr():
 78     """
 79     description:  獲取當前時間的可讀形式字符串
 80     return:       Mon May 13 11:27:42 2019 -> str
 81     """
 82     return time.ctime()
 83 
 84 
 85 def getCurrentTimeStrByTuple(tupleTime=time.localtime()):
 86     """
 87     description:  獲取指定時間的可讀形式字符串
 88     tupleTime:    時間元組 可通過time.localtime() or datetime.datetime.now().timetuple()獲取 默認當前時間的元組
 89     return:       Mon May 13 11:27:42 2019 -> str
 90     """
 91     return time.asctime(tupleTime)
 92 
 93 
 94 def sleepTime():
 95     """
 96     description:  推遲調用線程的運行
 97     """
 98     for i in range(4):
 99         print(i)
100         time.sleep(3)
101 
102 
103 # ======================
104 # ====== datetime ======
105 # ======================
106 
107 
108 def getNowDateTime():
109     """
110     description:  獲取當前日期&時間
111     return:       2019-05-13 14:41:15 -> str
112     """
113     timestamps = str(datetime.datetime.now()).split(".")[0]
114     return timestamps
115 
116 
117 def getNowTime():
118     """
119     description:  獲取當前時間
120     return:       14:41:15 -> str
121     """
122     timestamps = str(datetime.datetime.now().time()).split(".")[0]
123     return timestamps
124 
125 
126 def getTodayDate():
127     """
128     description:  獲取當前日期
129     return:       2019-05-13 -> str
130     tipe:         datetime.datetime.now().date()有相同效果
131     """
132     timestamps = str(datetime.date.today())
133     return timestamps
134 
135 
136 def getTimeDate(times=time.time()):
137     """
138     description:  獲取指定時間戳的日期
139     time:         秒 默認當前時間
140     return:       2019-05-13 -> str
141     tips:         一天86400秒
142     """
143     timestamps = str(datetime.date.fromtimestamp(round(times)))
144     return timestamps
145 
146 
147 # 獲取距離現在時間的任意時間的日期     正數 加,負數 減  return:2019-05-12
148 def getAnyDateTime(day, hour=0, min=0, sec=0):
149     """
150     description:  獲取距離現在時間的任意時間的日期&時間
151     day:          天數 1代表當前時間+1天    -1代表當前時間-1天
152     hour:         小時 2代表當前時間+2h     -2代表當前時間-2h     默認=0
153     min:          分鍾 30代表當前時間+30min -30代表當前時間-30m   默認=0
154     sec:          秒   120代表當前時間+120s -120代表當前時間-120s 默認=0
155     return:       2019-05-15 15:37:41 -> str
156     """
157     return str(datetime.datetime.now() + datetime.timedelta(days=day, hours=hour, minutes=min, seconds=sec)).split(".")[0]
158 
159 
160 def getAnyDateSecondTime(day, hour=0, min=0, sec=0):
161     """
162     description:  獲取距離現在時間的任意時間的秒數
163     day:          天數 1代表當前時間+1天    -1代表當前時間-1天
164     hour:         小時 2代表當前時間+2h     -2代表當前時間-2h     默認=0
165     min:          分鍾 30代表當前時間+30min -30代表當前時間-30m   默認=0
166     sec:          秒   120代表當前時間+120s -120代表當前時間-120s 默認=0
167     return:       1557902182 -> str
168     """
169     anyDay = datetime.datetime.now() + datetime.timedelta(days=day, hours=hour, minutes=min, seconds=sec)
170     return str(round(time.mktime(anyDay.timetuple())))
171 
172 
173 def getTodayTime():
174     """
175     description:  獲取當天0點的時間戳
176     return:       1557676800 -> str
177     """
178     return str(round(time.mktime(datetime.date.today().timetuple())))
179 
180 
181 def getCurrentWeekTime():
182     """
183     description:  獲取本周周一0點
184     return:       1557676800 -> str
185     tips:         可替換成: timestamps = time.mktime(time.strptime(time.strftime("%Y-%m-%d", time.localtime(times)), "%Y-%m-%d"))
186     """
187     week = int(time.strftime("%w", time.localtime()))
188     times = round(time.time()) - (week - 1) * 86400
189     timestamps = time.mktime(datetime.date.fromtimestamp(times).timetuple())
190     return str(round(timestamps))
191 
192 
193 def test():
194     print(getCurrentMilliSecondTime())
195     print(getCurrentSecondTime())
196     print(getCurrentFormatTimeStr())
197     print(getCurrentTimeTupleByFormatStr())
198     print("=======")
199     print(getCurrentTimeStr())
200     print(getCurrentTimeStrByTuple(time.localtime()))
201     print(getTimeByTuple(time.localtime()))
202     print("=======")
203     print(getNowDateTime())
204     print(getNowTime())
205     print(getNowDateTime())
206     print(getTodayDate())
207     print(getTimeDate(time.time() - 86400))
208     print("=======")
209     print(getAnyDateTime(2))
210     print(getAnyDateSecondTime(2))
211     print("=======")
212     print(getTodayTime())
213     print(getCurrentWeekTime())
214 
215 
216 if __name__ == '__main__':
217     print(test())


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM