Python time module

本文详细介绍了Python中的time模块,包括其提供的多种操作时间的函数。解释了如何使用time模块进行时间转换、获取当前时间以及时间格式化等常见任务。

Python标准库系列文章目录

python内建模块
collections 模块:deque双向队列
queue module:队列、优先级队列
sortedcontainers:有序列表、有序字典和有序集合



描述

time模块提供了多种操纵时间的函数
有两种方式表述时间。
1、xxxxxxxxx.xxxxxx秒,周期为epoch,此法为 UTC(a.k.a. GMT)
2、tuple(int1, int2, int3, int4, int5, int6, int7, in8, int9)
| | |
|–|:–|–|
| 1 |year(including century, e.g. 198) |
| 2| month(1-12)|
| 3 | day(1-31)|
| 4 | hours(0-23)|
| 5 | minutes(0-59)|
| 6 | seconds(0-59)|
| 7 | weekday(0-6, Monday is 0)|
| 8 | Julian day(day in the year, 1-366)|
|9|DST(Daylight Savings Time) flag(-1,0,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.


一、类

builtins.tuple(builtins.object)
struct_time

class struct_time(builtins.tuple)
 |  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.

二、函数

namereturne.g.
asctimeright-aligned 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.
输入:第二种表示方式,若为空默认输入localtime()
输出:str格式的当前时间
asctime()
返回当前系统时间
“Sat Jan 15 21:59:40 2022”
clockclock() -> floating point number
返回CPU时间or 实时,从进程开始或者第一次调用clock()
这和系统记录一样精确
返回距离第一次调用clock()过了多少秒,精确到小数点后7位
ctime输入:时间的第一种表示方式,若为空,默认返回当前时间
返回:当前时间str
ctime()返回结果同asctime()
gmtime
不太能和其它函数兼容
输入:seconds,若为空则为当前时间
输出:struct_time (tuple)
该函数输入和返回都为英国0经度的时间
将时间的第一种表示方式转化为时间的第二种表示方式
localtime输入:seconds,若为空则为当前时间
输出:struct_time (tuple)
将时间的第一种表示方式转化为时间的第二种表示方式
mktime输入:struct_time (tuple),不能为空
返回:floating point number
将时间的第二种表示方式转化为时间的第一种表示方式
该输出精度较低
monotonic获取单调时钟的值,仅连续调用的结果之间的差有效
在长时间运行过程中测量经过时间的方法
perf_count有点像monotonic但精度更高
sleep程序暂停xx.xx秒
time返回时间的第一种表示方式
### Python NumPy Module Usage and Documentation NumPy, short for Numerical Python, is a fundamental package required for scientific computing with Python. This library supports large, multi-dimensional arrays and matrices along with an extensive collection of high-level mathematical functions to operate on these arrays[^1]. #### Importing NumPy To use NumPy within a Python script or interactive session, one must first import it: ```python import numpy as np ``` This line imports the NumPy module under the alias `np`, which allows users to call its methods using this shorter name. #### Creating Arrays One can create NumPy arrays from lists or tuples by calling `np.array()`: ```python a = np.array([1, 2, 3]) b = np.array([[1, 2], [3, 4]]) ``` For generating sequences of numbers, there are several useful commands like `arange` (similar to range but returns an array), `linspace` (creates evenly spaced values over specified intervals), and more specialized ones such as `zeros`, `ones`, etc.[^2] #### Basic Operations Element-wise operations between two same-sized arrays work intuitively due to broadcasting rules that automatically align shapes when performing arithmetic operations: ```python c = a + b[:,0] # Adds column vector 'b' elementwise to row vector 'a' d = c * 2 # Multiplies each element in array 'c' by scalar value 2 e = d ** .5 # Computes square root of every item in resulting array 'd' ``` Matrix multiplication uses either dot product (`@`) operator introduced since Python 3.5 or function `dot()`. For example, ```python f = e @ b.T # Matrix multiply transposed matrix 'b' against diagonalized version of itself. g = np.dot(e,b.T)# Equivalent alternative syntax using explicit method invocation instead of infix notation. ``` #### Indexing & Slicing Indexing works similarly to standard Python lists; however, slicing offers additional flexibility through advanced indexing techniques allowing selection based upon boolean masks, integer indices, field names, among others: ```python h = g[::2,:] # Selects alternate rows starting at index zero up until end while keeping all columns intact. i = h[h>mean(h)]# Filters out elements below average across entire submatrix defined previously. j = i['field'] # Retrieves specific structured dtype component assuming original data contained named fields. ``` The official documentation serves as comprehensive resource covering installation instructions, tutorials aimed towards beginners alongside detailed API reference material suitable even experts seeking deeper understanding about particular aspects concerning usage patterns associated specifically around numerical computations performed efficiently via optimized C code behind scenes whenever possible during execution time depending upon underlying hardware capabilities available system-wide including parallel processing support where applicable provided appropriate flags set correctly beforehand compilation stage prior runtime environment setup completion process initialization sequence order matters significantly impacting overall performance characteristics observed empirically benchmark tests conducted periodically maintain quality assurance standards expected professional software development practices industry wide consensus best practice guidelines established community leaders recognized authority figures respected widely amongst peers contributing actively open source projects hosted popular platforms GitHub Bitbucket GitLab et al hosting services utilized collaboratively distributed teams working remotely geographically dispersed locations globally connected internet infrastructure enabling seamless collaboration asynchronous communication channels chat forums mailing lists issue trackers project management tools task assignment workflow automation pipelines continuous integration testing deployment strategies implemented robust security measures protecting sensitive information privacy concerns addressed appropriately legal compliance regulations followed strictly adhered ethical considerations taken seriously corporate social responsibility initiatives promoted positively impactful societal contributions made voluntarily beyond mere profit motives driving commercial enterprises private sector organizations public institutions governmental agencies alike striving achieve common goals shared vision mission statement articulated clearly communicated transparently stakeholders involved informed decision making processes inclusive diverse perspectives considered respectfully dialogue encouraged constructive feedback welcomed openly embraced culture innovation fostered creativity nurtured experimentation allowed fail fast learn quicker adapt better survive longer thrive sustainably long term success achieved mutually beneficial outcomes realized collectively effort teamwork synergy amplified exponentially greater than sum individual parts combined together harmoniously functioning well-oiled machine operating smoothly efficient manner optimal productivity levels reached consistently maintained over extended periods sustained growth trajectory projected future outlook bright promising potential awaits ahead horizon visible clear sight unobstructed view forward looking anticipation excitement builds momentum gathers steam propels onward upward journey continues relentless pursuit excellence never settles mediocrity always strives higher aims reach peak pinnacle achievement ultimate fulfillment realization dreams aspirations ambitions fulfilled completely wholeheartedly dedicated fully committed unwavering resolve steadfast determination perseverance tenacity grit resilience strength character tested tried true proven reliable trustworthy dependable solid foundation built strong roots deep planted firmly grounded stable base secure footing steady stance balanced equilibrium centered focus concentration sharp awareness alert presence mindful attention present moment living life fullest experiencing reality deeply profoundly meaningful way truly authentic self expression genuine connection relationships formed bonds strengthened unity harmony cohesiveness collective consciousness raised elevated expanded broadened widened horizons opened new possibilities explored unknown territories ventured into uncharted waters navigated treacherous seas sailed smooth sailing calm waters peaceful tranquility serenity inner peace attained outer world reflected internal state manifested outward appearance radiates positive energy attracts similar vibrations resonant frequency matches aligned attuned synchronized harmonious flow experienced effortlessly naturally
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值