天天看點

python子產品之time子產品

在我們學習的過程中,肯定會用到各種各樣的子產品。是以今天我們從time子產品開始學習

首先我們在使用某個子產品的時候,肯定要先導入這個子產品

 而當我們想看看這個子產品是幹什麼的,我們可以使用help函數來看

1 "E:\Program Files (x86)\python_3.8\python.exe" D:/Application/pycharm_works/_1/test/python子產品之time子產品.py
  2 Help on built-in module time:
  3 
  4 NAME
  5     time - This module provides various functions to manipulate time values.
  6 
  7 DESCRIPTION
  8     There are two standard representations of time.  One is the number
  9     of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer
 10     or a floating point number (to represent fractions of seconds).
 11     The Epoch is system-defined; on Unix, it is generally January 1st, 1970.
 12     The actual value can be retrieved by calling gmtime(0).
 13     
 14     The other representation is a tuple of 9 integers giving local time.
 15     The tuple items are:
 16       year (including century, e.g. 1998)
 17       month (1-12)
 18       day (1-31)
 19       hours (0-23)
 20       minutes (0-59)
 21       seconds (0-59)
 22       weekday (0-6, Monday is 0)
 23       Julian day (day in the year, 1-366)
 24       DST (Daylight Savings Time) flag (-1, 0 or 1)
 25     If the DST flag is 0, the time is given in the regular time zone;
 26     if it is 1, the time is given in the DST time zone;
 27     if it is -1, mktime() should guess based on the date and time.
 28 
 29 CLASSES
 30     builtins.tuple(builtins.object)
 31         struct_time
 32     
 33     class struct_time(builtins.tuple)
 34      |  struct_time(iterable=(), /)
 35      |  
 36      |  The time value as returned by gmtime(), localtime(), and strptime(), and
 37      |  accepted by asctime(), mktime() and strftime().  May be considered as a
 38      |  sequence of 9 integers.
 39      |  
 40      |  Note that several fields' values are not the same as those defined by
 41      |  the C language standard for struct tm.  For example, the value of the
 42      |  field tm_year is the actual year, not year - 1900.  See individual
 43      |  fields' descriptions for details.
 44      |  
 45      |  Method resolution order:
 46      |      struct_time
 47      |      builtins.tuple
 48      |      builtins.object
 49      |  
 50      |  Methods defined here:
 51      |  
 52      |  __reduce__(...)
 53      |      Helper for pickle.
 54      |  
 55      |  __repr__(self, /)
 56      |      Return repr(self).
 57      |  
 58      |  ----------------------------------------------------------------------
 59      |  Static methods defined here:
 60      |  
 61      |  __new__(*args, **kwargs) from builtins.type
 62      |      Create and return a new object.  See help(type) for accurate signature.
 63      |  
 64      |  ----------------------------------------------------------------------
 65      |  Data descriptors defined here:
 66      |  
 67      |  tm_gmtoff
 68      |      offset from UTC in seconds
 69      |  
 70      |  tm_hour
 71      |      hours, range [0, 23]
 72      |  
 73      |  tm_isdst
 74      |      1 if summer time is in effect, 0 if not, and -1 if unknown
 75      |  
 76      |  tm_mday
 77      |      day of month, range [1, 31]
 78      |  
 79      |  tm_min
 80      |      minutes, range [0, 59]
 81      |  
 82      |  tm_mon
 83      |      month of year, range [1, 12]
 84      |  
 85      |  tm_sec
 86      |      seconds, range [0, 61])
 87      |  
 88      |  tm_wday
 89      |      day of week, range [0, 6], Monday is 0
 90      |  
 91      |  tm_yday
 92      |      day of year, range [1, 366]
 93      |  
 94      |  tm_year
 95      |      year, for example, 1993
 96      |  
 97      |  tm_zone
 98      |      abbreviation of timezone name
 99      |  
100      |  ----------------------------------------------------------------------
101      |  Data and other attributes defined here:
102      |  
103      |  n_fields = 11
104      |  
105      |  n_sequence_fields = 9
106      |  
107      |  n_unnamed_fields = 0
108      |  
109      |  ----------------------------------------------------------------------
110      |  Methods inherited from builtins.tuple:
111      |  
112      |  __add__(self, value, /)
113      |      Return self+value.
114      |  
115      |  __contains__(self, key, /)
116      |      Return key in self.
117      |  
118      |  __eq__(self, value, /)
119      |      Return self==value.
120      |  
121      |  __ge__(self, value, /)
122      |      Return self>=value.
123      |  
124      |  __getattribute__(self, name, /)
125      |      Return getattr(self, name).
126      |  
127      |  __getitem__(self, key, /)
128      |      Return self[key].
129      |  
130      |  __getnewargs__(self, /)
131      |  
132      |  __gt__(self, value, /)
133      |      Return self>value.
134      |  
135      |  __hash__(self, /)
136      |      Return hash(self).
137      |  
138      |  __iter__(self, /)
139      |      Implement iter(self).
140      |  
141      |  __le__(self, value, /)
142      |      Return self<=value.
143      |  
144      |  __len__(self, /)
145      |      Return len(self).
146      |  
147      |  __lt__(self, value, /)
148      |      Return self<value.
149      |  
150      |  __mul__(self, value, /)
151      |      Return self*value.
152      |  
153      |  __ne__(self, value, /)
154      |      Return self!=value.
155      |  
156      |  __rmul__(self, value, /)
157      |      Return value*self.
158      |  
159      |  count(self, value, /)
160      |      Return number of occurrences of value.
161      |  
162      |  index(self, value, start=0, stop=9223372036854775807, /)
163      |      Return first index of value.
164      |      
165      |      Raises ValueError if the value is not present.
166 
167 FUNCTIONS
168     asctime(...)
169         asctime([tuple]) -> string
170         
171         Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
172         When the time tuple is not present, current time as returned by localtime()
173         is used.
174     
175     ctime(...)
176         ctime(seconds) -> string
177         
178         Convert a time in seconds since the Epoch to a string in local time.
179         This is equivalent to asctime(localtime(seconds)). When the time tuple is
180         not present, current time as returned by localtime() is used.
181     
182     get_clock_info(...)
183         get_clock_info(name: str) -> dict
184         
185         Get information of the specified clock.
186     
187     gmtime(...)
188         gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,
189                                tm_sec, tm_wday, tm_yday, tm_isdst)
190         
191         Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
192         GMT).  When 'seconds' is not passed in, convert the current time instead.
193         
194         If the platform supports the tm_gmtoff and tm_zone, they are available as
195         attributes only.
196     
197     localtime(...)
198         localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
199                                   tm_sec,tm_wday,tm_yday,tm_isdst)
200         
201         Convert seconds since the Epoch to a time tuple expressing local time.
202         When 'seconds' is not passed in, convert the current time instead.
203     
204     mktime(...)
205         mktime(tuple) -> floating point number
206         
207         Convert a time tuple in local time to seconds since the Epoch.
208         Note that mktime(gmtime(0)) will not generally return zero for most
209         time zones; instead the returned value will either be equal to that
210         of the timezone or altzone attributes on the time module.
211     
212     monotonic(...)
213         monotonic() -> float
214         
215         Monotonic clock, cannot go backward.
216     
217     monotonic_ns(...)
218         monotonic_ns() -> int
219         
220         Monotonic clock, cannot go backward, as nanoseconds.
221     
222     perf_counter(...)
223         perf_counter() -> float
224         
225         Performance counter for benchmarking.
226     
227     perf_counter_ns(...)
228         perf_counter_ns() -> int
229         
230         Performance counter for benchmarking as nanoseconds.
231     
232     process_time(...)
233         process_time() -> float
234         
235         Process time for profiling: sum of the kernel and user-space CPU time.
236     
237     process_time_ns(...)
238         process_time() -> int
239         
240         Process time for profiling as nanoseconds:
241         sum of the kernel and user-space CPU time.
242     
243     sleep(...)
244         sleep(seconds)
245         
246         Delay execution for a given number of seconds.  The argument may be
247         a floating point number for subsecond precision.
248     
249     strftime(...)
250         strftime(format[, tuple]) -> string
251         
252         Convert a time tuple to a string according to a format specification.
253         See the library reference manual for formatting codes. When the time tuple
254         is not present, current time as returned by localtime() is used.
255         
256         Commonly used format codes:
257         
258         %Y  Year with century as a decimal number.
259         %m  Month as a decimal number [01,12].
260         %d  Day of the month as a decimal number [01,31].
261         %H  Hour (24-hour clock) as a decimal number [00,23].
262         %M  Minute as a decimal number [00,59].
263         %S  Second as a decimal number [00,61].
264         %z  Time zone offset from UTC.
265         %a  Locale's abbreviated weekday name.
266         %A  Locale's full weekday name.
267         %b  Locale's abbreviated month name.
268         %B  Locale's full month name.
269         %c  Locale's appropriate date and time representation.
270         %I  Hour (12-hour clock) as a decimal number [01,12].
271         %p  Locale's equivalent of either AM or PM.
272         
273         Other codes may be available on your platform.  See documentation for
274         the C library strftime function.
275     
276     strptime(...)
277         strptime(string, format) -> struct_time
278         
279         Parse a string to a time tuple according to a format specification.
280         See the library reference manual for formatting codes (same as
281         strftime()).
282         
283         Commonly used format codes:
284         
285         %Y  Year with century as a decimal number.
286         %m  Month as a decimal number [01,12].
287         %d  Day of the month as a decimal number [01,31].
288         %H  Hour (24-hour clock) as a decimal number [00,23].
289         %M  Minute as a decimal number [00,59].
290         %S  Second as a decimal number [00,61].
291         %z  Time zone offset from UTC.
292         %a  Locale's abbreviated weekday name.
293         %A  Locale's full weekday name.
294         %b  Locale's abbreviated month name.
295         %B  Locale's full month name.
296         %c  Locale's appropriate date and time representation.
297         %I  Hour (12-hour clock) as a decimal number [01,12].
298         %p  Locale's equivalent of either AM or PM.
299         
300         Other codes may be available on your platform.  See documentation for
301         the C library strftime function.
302     
303     thread_time(...)
304         thread_time() -> float
305         
306         Thread time for profiling: sum of the kernel and user-space CPU time.
307     
308     thread_time_ns(...)
309         thread_time() -> int
310         
311         Thread time for profiling as nanoseconds:
312         sum of the kernel and user-space CPU time.
313     
314     time(...)
315         time() -> floating point number
316         
317         Return the current time in seconds since the Epoch.
318         Fractions of a second may be present if the system clock provides them.
319     
320     time_ns(...)
321         time_ns() -> int
322         
323         Return the current time in nanoseconds since the Epoch.
324 
325 DATA
326     altzone = -32400
327     daylight = 0
328     timezone = -28800
329     tzname = ('中國标準時間', '中國夏令時')
330 
331 FILE
332     (built-in)
333 
334 
335 None
336 
337 Process finished with exit code 0           

View Code

 那麼接下來我們挨個來看看

1. time.time()為目前時間戳,從1900年開始到目前時間的秒數

print(help(time.time)) # 列印幫助資訊
print(time.time()) #1610720236.653394 # 列印目前時間戳           
1 Help on built-in function time in module time:
 2 
 3 time(...)
 4     time() -> floating point number
 5     
 6     Return the current time in seconds since the Epoch.
 7     Fractions of a second may be present if the system clock provides them.
 8 
 9 None
10 1610727247.1696546           

View Code

2. time.sleep(secs) 讓程式暫停secs秒

1 print(help(time.sleep)) # 列印幫助資訊
2 time.sleep(3) # 暫停3秒           
1 Help on built-in function sleep in module time:
2 
3 sleep(...)
4     sleep(seconds)
5     
6     Delay execution for a given number of seconds.  The argument may be
7     a floating point number for subsecond precision.
8 
9 None           

View Code

3.time.gmtime() 結構化時間,不過要注意的一點是這個時間是世界标準時間(格林尼治時間)

1 print(help(time.gmtime)) # 列印幫助資訊
2 print(time.gmtime()) # 結構化時間 time.struct_time(tm_year=2021, tm_mon=1, tm_mday=15, tm_hour=14, tm_min=22, tm_sec=30, tm_wday=4, tm_yday=15, tm_isdst=0)           
1 Help on built-in function gmtime in module time:
 2 
 3 gmtime(...)
 4     gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,
 5                            tm_sec, tm_wday, tm_yday, tm_isdst)
 6     
 7     Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
 8     GMT).  When 'seconds' is not passed in, convert the current time instead.
 9     
10     If the platform supports the tm_gmtoff and tm_zone, they are available as
11     attributes only.
12 
13 None
14 time.struct_time(tm_year=2021, tm_mon=1, tm_mday=15, tm_hour=16, tm_min=16, tm_sec=39, tm_wday=4, tm_yday=15, tm_isdst=0)           

View Code

不過這時肯定有人該問了,那我們的當地時間怎麼表示呢,是以我們來介紹下一個

4.time.localtime()結構化時間,目前時間

1 print(help(time.localtime)) # 列印幫助資訊
2 print(time.localtime()) # 目前結構化時間           
1 Help on built-in function localtime in module time:
 2 
 3 localtime(...)
 4     localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
 5                               tm_sec,tm_wday,tm_yday,tm_isdst)
 6     
 7     Convert seconds since the Epoch to a time tuple expressing local time.
 8     When 'seconds' is not passed in, convert the current time instead.
 9 
10 None
11 time.struct_time(tm_year=2021, tm_mon=1, tm_mday=16, tm_hour=0, tm_min=17, tm_sec=49, tm_wday=5, tm_yday=16, tm_isdst=0)           

View Code

總說結構化時間,那結構化時間是什麼呢,我們來看看裡面的參數

1 我們來拿上面這個例子來解釋:
 2 
 3 tm_year=2021     目前所在年
 4 tm_mon=1         目前所在月
 5 tm_mday=15       目前所在天
 6 tm_hour=23       目前所在時
 7 tm_min=18        目前所在分
 8 tm_sec=57        目前所在秒
 9 tm_wday=4        目前周的第幾天
10 tm_yday=15       目前年的第幾天           

但是有時候我們需要的并不是結構化時間,而是類似于 2021-01-15 23:28:26 這樣的格式化時間,那我們應該怎麼做呢?

6. time.strftime() 将結構話時間化為格式化時間

1 print(help(time.strftime)) # 列印幫助資訊
2 struct_time=time.localtime()
3 print(time.strftime("%Y-%m-%d %H:%M:%S",struct_time)) # 格式化時間           
1 Help on built-in function strftime in module time:
 2 
 3 strftime(...)
 4     strftime(format[, tuple]) -> string
 5     
 6     Convert a time tuple to a string according to a format specification.
 7     See the library reference manual for formatting codes. When the time tuple
 8     is not present, current time as returned by localtime() is used.
 9     
10     Commonly used format codes:
11     
12     %Y  Year with century as a decimal number.
13     %m  Month as a decimal number [01,12].
14     %d  Day of the month as a decimal number [01,31].
15     %H  Hour (24-hour clock) as a decimal number [00,23].
16     %M  Minute as a decimal number [00,59].
17     %S  Second as a decimal number [00,61].
18     %z  Time zone offset from UTC.
19     %a  Locale's abbreviated weekday name.
20     %A  Locale's full weekday name.
21     %b  Locale's abbreviated month name.
22     %B  Locale's full month name.
23     %c  Locale's appropriate date and time representation.
24     %I  Hour (12-hour clock) as a decimal number [01,12].
25     %p  Locale's equivalent of either AM or PM.
26     
27     Other codes may be available on your platform.  See documentation for
28     the C library strftime function.
29 
30 None
31 2021-01-16 00:18:38           

View Code

同樣這裡為什麼要寫成 "%Y-%m-%d %H:%M:%S" 呢,就是為了控制時間的格式。

那這些都表示什麼呢,我們來看看

1     %Y  Year with century as a decimal number.
 2     %m  Month as a decimal number [01,12].
 3     %d  Day of the month as a decimal number [01,31].
 4     %H  Hour (24-hour clock) as a decimal number [00,23].
 5     %M  Minute as a decimal number [00,59].
 6     %S  Second as a decimal number [00,61].
 7     %z  Time zone offset from UTC.
 8     %a  Locale's abbreviated weekday name.
 9     %A  Locale's full weekday name.
10     %b  Locale's abbreviated month name.
11     %B  Locale's full month name.
12     %c  Locale's appropriate date and time representation.
13     %I  Hour (12-hour clock) as a decimal number [01,12].
14     %p  Locale's equivalent of either AM or PM.           

不過似乎也可以單獨使用   time.strftime(),我們來看看結果,但是我們必須要把格式加上,如下所示:

print(time.strftime("%Y-%m-%d %H:%M:%S")) # 格式化時間  
# 2021-01-15 23:36:49           

那麼,有時候我們也需要把格式化時間轉化為結構化時間來使用,這時我們僅僅需要看看接下來的知識就能掌握

7. time.strptime() 将格式化時間(字元串)轉化為結構化時間

print(help(time.strftime))
print(time.strftime("%Y-%m-%d %H:%M:%S")) # 格式化時間  
# 2021-01-15 23:36:49           
1 Help on built-in function strftime in module time:
 2 
 3 strftime(...)
 4     strftime(format[, tuple]) -> string
 5     
 6     Convert a time tuple to a string according to a format specification.
 7     See the library reference manual for formatting codes. When the time tuple
 8     is not present, current time as returned by localtime() is used.
 9     
10     Commonly used format codes:
11     
12     %Y  Year with century as a decimal number.
13     %m  Month as a decimal number [01,12].
14     %d  Day of the month as a decimal number [01,31].
15     %H  Hour (24-hour clock) as a decimal number [00,23].
16     %M  Minute as a decimal number [00,59].
17     %S  Second as a decimal number [00,61].
18     %z  Time zone offset from UTC.
19     %a  Locale's abbreviated weekday name.
20     %A  Locale's full weekday name.
21     %b  Locale's abbreviated month name.
22     %B  Locale's full month name.
23     %c  Locale's appropriate date and time representation.
24     %I  Hour (12-hour clock) as a decimal number [01,12].
25     %p  Locale's equivalent of either AM or PM.
26     
27     Other codes may be available on your platform.  See documentation for
28     the C library strftime function.
29 
30 None
31 2021-01-16 00:20:46           

View Code

當然以上隻是一個舉例,具體我們可以采用如下方式:

a=time.strptime("2021-01-15 22:26:28","%Y-%m-%d %H:%M:%S")
print(a.tm_yday)   # 15
print(a.tm_wday)   # 4           

最後,我們快接近了尾聲,最後我們再介紹兩個就結束了

8. time.ctime() 将所給時間戳轉變為一個格式化時間

1 print(help(time.ctime))  # 将時間戳轉變為一個格式化時間
2 print(time.ctime())   # 如果不帶參數則預設為目前時間戳
3 print(time.ctime(12412415))           
1 Help on built-in function ctime in module time:
 2 
 3 ctime(...)
 4     ctime(seconds) -> string
 5     
 6     Convert a time in seconds since the Epoch to a string in local time.
 7     This is equivalent to asctime(localtime(seconds)). When the time tuple is
 8     not present, current time as returned by localtime() is used.
 9 
10 None
11 Sat Jan 16 00:21:56 2021
12 Sun May 24 23:53:35 1970           

View Code

9.time.mktime()  将所給結構化時間轉化為時間戳

1 print(help(time.ctime))  # 列印幫助資訊
2 print(time.mktime(time.localtime())) # 将結構化時間轉化為時間戳           
1 Help on built-in function ctime in module time:
 2 
 3 ctime(...)
 4     ctime(seconds) -> string
 5     
 6     Convert a time in seconds since the Epoch to a string in local time.
 7     This is equivalent to asctime(localtime(seconds)). When the time tuple is
 8     not present, current time as returned by localtime() is used.
 9 
10 None
11 1610727764.0           

View Code

不過值得一提的是,這種方式得到的時間戳精度要比time.time()低的多

最後,在提供一種其他求目前時間的方法

import datetime

print(datetime.datetime.now())  # 2021-01-15 23:55:48.985808           

本次time子產品便到此結束,其他子產品下次講解