python之time模块
在我们学习的过程中,肯定会用到各种各样的模块。所以今天我们从time模块开始学习
首先我们在使用某个模块的时候,肯定要先导入这个模块
import time
而当我们想看看这个模块是干什么的,我们可以使用help函数来看
print(help(time)) # 打印帮助信息
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模块便到此结束,其他模块下次讲解