系统城装机大师 - 固镇县祥瑞电脑科技销售部宣传站!

当前位置:首页 > 脚本中心 > python > 详细页面

Python学习之time模块的基本使用

时间:2021-01-17来源:www.pcxitongcheng.com作者:电脑系统城

前言

在我们学习的过程中,肯定会用到各种各样的模块。所以今天我们从time模块开始学习

首先我们在使用某个模块的时候,肯定要先导入这个模块

1 import time

 而当我们想看看这个模块是干什么的,我们可以使用help函数来看

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

 那么接下来我们挨个来看看

1. time.time()为当前时间戳,从1900年开始到当前时间的秒数

1
2
print(help(time.time)) # 打印帮助信息
print(time.time()) #1610720236.653394 # 打印当前时间戳
1
2
3
4
5
6
7
8
9
10
Help on built-in function time in module time:
 
time(...)
 time() -> floating point number
 
 Return the current time in seconds since the Epoch.
 Fractions of a second may be present if the system clock provides them.
 
None
1610727247.1696546

2. time.sleep(secs) 让程序暂停secs秒

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

3.time.gmtime() 结构化时间,不过要注意的一点是这个时间是世界标准时间(格林尼治时间)

1
2
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
2
3
4
5
6
7
8
9
10
11
12
13
14
Help on built-in function gmtime in module time:
 
gmtime(...)
 gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,
       tm_sec, tm_wday, tm_yday, tm_isdst)
 
 Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
 GMT). When 'seconds' is not passed in, convert the current time instead.
 
 If the platform supports the tm_gmtoff and tm_zone, they are available as
 attributes only.
 
None
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)

不过这时肯定有人该问了,那我们的当地时间怎么表示呢,所以我们来介绍下一个

4.time.localtime()结构化时间,当前时间

1
2
1 print(help(time.localtime)) # 打印帮助信息
2 print(time.localtime()) # 当前结构化时间
1
2
3
4
5
6
7
8
9
10
11
Help on built-in function localtime in module time:
 
localtime(...)
 localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
        tm_sec,tm_wday,tm_yday,tm_isdst)
 
 Convert seconds since the Epoch to a time tuple expressing local time.
 When 'seconds' is not passed in, convert the current time instead.
 
None
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)

总说结构化时间,那结构化时间是什么呢,我们来看看里面的参数

我们来拿上面这个例子来解释:

tm_year=2021     当前所在年
tm_mon=1         当前所在月
tm_mday=15       当前所在天
tm_hour=23       当前所在时
tm_min=18        当前所在分
tm_sec=57        当前所在秒
tm_wday=4        当前周的第几天
tm_yday=15       当前年的第几天

但是有时候我们需要的并不是结构化时间,而是类似于 2021-01-15 23:28:26 这样的格式化时间,那我们应该怎么做呢?

6. time.strftime() 将结构话时间化为格式化时间

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

同样这里为什么要写成 "%Y-%m-%d %H:%M:%S" 呢,就是为了控制时间的格式。

那这些都表示什么呢,我们来看看

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

不过似乎也可以单独使用   time.strftime(),我们来看看结果,但是我们必须要把格式加上,如下所示:

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

那么,有时候我们也需要把格式化时间转化为结构化时间来使用,这时我们仅仅需要看看接下来的知识就能掌握

7. time.strptime() 将格式化时间(字符串)转化为结构化时间

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

当然以上只是一个举例,具体我们可以采用如下方式:

1
2
3
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
2
3
1 print(help(time.ctime)) # 将时间戳转变为一个格式化时间
2 print(time.ctime())  # 如果不带参数则默认为当前时间戳
3 print(time.ctime(12412415))
1
2
3
4
5
6
7
8
9
10
11
12
Help on built-in function ctime in module time:
 
ctime(...)
  ctime(seconds) -> string
 
  Convert a time in seconds since the Epoch to a string in local time.
  This is equivalent to asctime(localtime(seconds)). When the time tuple is
  not present, current time as returned by localtime() is used.
 
None
Sat Jan 16 00:21:56 2021
Sun May 24 23:53:35 1970

9.time.mktime()  将所给结构化时间转化为时间戳

1
2
1 print(help(time.ctime)) # 打印帮助信息
2 print(time.mktime(time.localtime())) # 将结构化时间转化为时间戳
1
2
3
4
5
6
7
8
9
10
11
Help on built-in function ctime in module time:
 
ctime(...)
  ctime(seconds) -> string
 
  Convert a time in seconds since the Epoch to a string in local time.
  This is equivalent to asctime(localtime(seconds)). When the time tuple is
  not present, current time as returned by localtime() is used.
 
None
1610727764.0

不过值得一提的是,这种方式得到的时间戳精度要比time.time()低的多

最后,在提供一种其他求当前时间的方法

1
2
3
import datetime
 
print(datetime.datetime.now()) # 2021-01-15 23:55:48.985808

本次time模块便到此结束,其他模块下次讲解

分享到:

相关信息

系统教程栏目

栏目热门教程

人气教程排行

站长推荐

热门系统下载