python之time模块

编程之家收集整理的这篇文章主要介绍了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, 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  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  the regular time zone;
 26     if it is 1,1)"> the DST time zone;
 27     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(),1)">and strptime(),1)">and
 37      |  accepted by asctime(),mktime()  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,1)">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  pickle.
 54      |  
 55      |  __repr__(self,1)"> 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)  accurate signature.
 63      |  
 64      |  ----------------------------------------------------------------------
 65      |  Data descriptors defined here:
 66      |  
 67      |  tm_gmtoff
 68      |      offset from UTC  seconds
 69      |  
 70      |  tm_hour
 71      |      hours,range [0,23]
 72      |  
 73      |  tm_isdst
 74      |      1 if summer time is in effect,1)">if not,1)">and -1 if unknown
 75      |  
 76      |  tm_mday
 77      |      day of month,range [1,31 78      |  
 79      |  tm_min
 80      |      minutes,59 81      |  
 82      |  tm_mon
 83      |      month of year,12 84      |  
 85      |  tm_sec
 86      |      seconds,61])
 87      |  
 88      |  tm_wday
 89      |      day of week,6],1)"> 0
 90      |  
 91      |  tm_yday
 92      |      day of year,366 93      |  
 94      |  tm_year
 95      |      year,1)">for example,1993
 96      |  
 97      |  tm_zone
 98      |      abbreviation of timezone name
 99      |  
100      |  ----------------------------------------------------------------------
101      |  Data  other attributes defined here:
102      |  
103      |  n_fields = 11
104      |  
105      |  n_sequence_fields = 9
106      |  
107      |  n_unnamed_fields =108      |  
109      |  ----------------------------------------------------------------------
110      |  Methods inherited  builtins.tuple:
111      |  
112      |  __add__(self,value,1)">113      |      Return self+value.
114      |  
115      |  __contains__(self,key,1)">116      |      Return key  self.
117      |  
118      |  __eq__(self,1)">119      |      Return self==120      |  
121      |  __ge__(self,1)">122      |      Return self>=123      |  
124      |  __getattribute__(self,name,1)">125      |      Return getattr(self,name).
126      |  
127      |  __getitem__(self,1)">128      |      Return self[key].
129      |  
130      |  __getnewargs__(self,1)">131      |  
132      |  __gt__(self,1)">133      |      Return self>134      |  
135      |  __hash__(self,1)">136      |      Return hash(self).
137      |  
138      |  __iter__(self,1)">139      |      Implement iter(self).
140      |  
141      |  __le__(self,1)">142      |      Return self<=143      |  
144      |  __len__(self,1)">145      |      Return len(self).
146      |  
147      |  __lt__(self,1)">148      |      Return self<149      |  
150      |  __mul__(self,1)">151      |      Return self*152      |  
153      |  __ne__(self,1)">154      |      Return self!=155      |  
156      |  __rmul__(self,1)">157      |      Return value*self.
158      |  
159      |  count(self,1)">160      |      Return number of occurrences of value.
161      |  
162      |  index(self,start=0,stop=9223372036854775807,1)">163      |      Return first index of value.
164      |      
165      |      Raises ValueError if the value 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  present,current time as returned by localtime()
173          used.
174     
175     ctime(...)
176         ctime(seconds) ->177         
178         Convert a time in seconds since the Epoch to a string  local time.
179         This is equivalent to asctime(localtime(seconds)). When the time tuple is
180         not present,current time as returned by localtime() 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' not passed ,convert the current time instead.
193         
194         If the platform supports the tm_gmtoff  tm_zone,they are available as
195         attributes only.
196     
197     localtime(...)
198         localtime([seconds]) ->199                                   tm_sec,1)">200         
201         Convert seconds since the Epoch to a time tuple expressing local time.
202         When 203     
204     mktime(...)
205         mktime(tuple) -> floating point number
206         
207         Convert a time tuple  local time to seconds since the Epoch.
208         Note that mktime(gmtime(0)) will not generally return zero  most
209         time zones; instead the returned value will either be equal to that
210         of the timezone  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 221     
222     perf_counter(...)
223         perf_counter() ->224         
225         Performance counter  benchmarking.
226     
227     perf_counter_ns(...)
228         perf_counter_ns() ->229         
230         Performance counter  benchmarking as nanoseconds.
231     
232     process_time(...)
233         process_time() ->234         
235         Process time for profiling: sum of the kernel and user-space cpu time.
236     
237     process_time_ns(...)
238         process_time() ->239         
240         Process time  profiling as nanoseconds:
241         sum of the kernel 242     
243     sleep(...)
244         sleep(seconds)
245         
246         Delay execution  a given number of seconds.  The argument may be
247         a floating point number  subsecond precision.
248     
249     strftime(...)
250         strftime(format[,tuple]) ->251         
252         Convert a time tuple to a string according to a format specification.
253         See the library reference manual  formatting codes. When the time tuple
254         255         
256         Commonly used format codes:
257         
258         %Y  Year with century as a decimal number.
259         %m  Month as a decimal number [01,1)">].
260         %d  Day of the month as a decimal number [01,1)">261         %H  Hour (24-hour clock) as a decimal number [00,1)">262         %M  Minute as a decimal number [00,1)">263         %S  Second as a decimal number [00,1)">264         %z  Time zone offset  UTC.
265         %a  Locales abbreviated weekday name.
266         %A  Locales full weekday name.
267         %b  Locales abbreviated month name.
268         %B  Locales full month name.
269         %c  Locales appropriate date and time representation.
270         %I  Hour (12-hour clock) as a decimal number [01,1)">271         %p  Locales 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  formatting codes (same as
281         strftime()).
282         
283 284         
285         %286         %m  Month as a decimal number [01,1)">287         %d  Day of the month as a decimal number [01,1)">288         %H  Hour (24-hour clock) as a decimal number [00,1)">289         %M  Minute as a decimal number [00,1)">290         %S  Second as a decimal number [00,1)">291         %z  Time zone offset 292         %a  Locale293         %A  Locale294         %b  Locale295         %B  Locale296         %c  Locale297         %I  Hour (12-hour clock) as a decimal number [01,1)">298         %p  Locale299         
300         Other codes may be available on your platform.  See documentation 301 302     
303     thread_time(...)
304         thread_time() ->305         
306         Thread time 307     
308     thread_time_ns(...)
309         thread_time() ->310         
311         Thread time 312         sum of the kernel 313     
314     time(...)
315         time() ->316         
317         Return the current time  seconds since the Epoch.
318         Fractions of a second may be present  the system clock provides them.
319     
320     time_ns(...)
321         time_ns() ->322         
323         Return the current time  nanoseconds since the Epoch.
324 
325 DATA
326     altzone = -32400
327     daylight =328     timezone = -28800
329     tzname = (中国标准时间',中国夏令时330 
331 FILE
332     (built-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  2 
 3 time(...)
 4     time() -> 5     
 6     Return the current time  7     Fractions of a second may be present  8 
 9 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 2 
3 sleep(...)
4     sleep(seconds)
5     
6     Delay execution 7     a floating point number 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)

in function gmtime gmtime(...)
 4     gmtime([seconds]) -> 5                            tm_sec,1)"> 6     
 7     Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
 8     GMT).  When  9     
10     If the platform supports the tm_gmtoff 11     attributes only.
12 
13 14 time.struct_time(tm_year=2021,tm_hour=16,tm_min=16,tm_sec=39,tm_isdst=0)
View Code

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

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

1 print(help(time.localtime)) print(time.localtime())  当前结构化时间

in function localtime localtime(...)
 4     localtime([seconds]) ->                              tm_sec,1)">    Convert seconds since the Epoch to a time tuple expressing local time.
 8     When  9 
10 11 time.struct_time(tm_year=2021,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))  格式化时间

in function strftime strftime(...)
 4     strftime(format[,1)"> 6     Convert a time tuple to a string according to a format specification.
 7     See the library reference manual  8         Commonly used format codes:
11     
12     %13     %m  Month as a decimal number [01,1)">14     %d  Day of the month as a decimal number [01,1)">15     %H  Hour (24-hour clock) as a decimal number [00,1)">16     %M  Minute as a decimal number [00,1)">17     %S  Second as a decimal number [00,1)">18     %z  Time zone offset 19     %a  Locale20     %A  Locale21     %b  Locale22     %B  Locale23     %c  Locale24     %I  Hour (12-hour clock) as a decimal number [01,1)">25     %p  Locale26     
27     Other codes may be available on your platform.  See documentation 28     the C library strftime function.
29 
30 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(),我们来看看结果,但是我们必须要把格式加上,如下所示:

"))  格式化时间  
# 2021-01-15 23:36:49

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

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

print(help(time.strftime))
print
(time.strftime( 2021-01-15 23:36:49

31 2021-01-16 00:20:46
View Code

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

a=time.strptime(2021-01-15 22:26:28"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))

in function ctime ctime(...)
 4     ctime(seconds) -> 6     Convert a time  7     This 11 Sat Jan 16 00:21:56 2021
12 Sun May 24 23:53:35 1970
View Code

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

1 print(time.mktime(time.localtime()))  将结构化时间转化为时间戳

11 1610727764.0
View Code

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

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

import datetime

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

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

 

相关文章

总结

以上是编程之家为你收集整理的python之time模块全部内容,希望文章能够帮你解决python之time模块所遇到的程序开发问题。

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您喜欢寻找一群志同道合、互帮互助的学习伙伴,可以点击下方链接加入:
编程之家官方1群:1065694478(已满)
编程之家官方2群:163560250(已满)
编程之家官方3群:312128206

猜你在找的Python相关文章

Python并不支持真正意义上的多线程。Python中提供了多线程包,但是如果你想通过多线程提高代码的速度,使用多线程包并不是个好主意。 Python中有一个被称为Global Interpreter
链表成对调换 class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param
前言 人生苦短,我用Python 1. Python环境的搭建 解释器和开发集成环境pycharm的安装还是比较简单的。 1.1 python解释器的安装 (1)到官网下载python解释器 下载地址
Windows下安装python 一、第一步点此链接先下载python 这里给出百度网盘的下载链接***python3.7.3***提取码:exko 请根据下图操作 自选安装的位置。不建议装在C盘里。
类型转换是指将一种数据类型转换为另一种数据类型。 int() - 将任何数据类型转换为整数类型 float() - 将任何数据类型转换为float类型 ord() - 将字符转换为整数 hex() -
已经pip安装好第三方库了,但是在pycharm中import还是标红,像下图:我记得上次重装系统,出现这种情况的时候,我重启一下pycharm就行了(但是感觉pycharm一开一关很费时间) 还有一
前言 本系列文默认各位有一定的C或C++基础,因为我是学了点C++的皮毛之后入手的Python,这里也要感谢齐锋学长送来的支持。本系列文默认各位会百度,会用在线编译器,因为我是突击学Python的,之
1.条件判断语句(if语句) 执⾏的流程: if语句在执⾏时,会先对条件表达式进⾏求值判断, 如果为True,则执⾏if后的语句 如果为False,则不执⾏ 语法: if 条件表达式 : 代码块 代码