Understanding python's built-in time module

Keywords: Python time

time

Parameterless function

Explain the timestamp, which is the number of seconds that have elapsed since January 1, 1970, at 00:00:00. Then you can understand the function below. The following code defaults from time import *

In secondsIn nanosecondsfunction
time()time_ns()Get the current timestamp
thread_time()thread_time_ns()Gets the CPU time of the current thread (without hibernation)
thread_time()thread_time_ns()Gets the CPU time of the current process (without hibernation)
monotonic()monotonic_ns()Gets the value of a monotonic clock
perf_counter()perf_counter_ns()Gets the value of a counter

Of the above five sets of functions, only the value of time.time() has absolute meaning, and all the other values have relative meaning.

By get_ Clock_ The info function looks at the characteristics of these clocks, and their inputs and outputs are

implementationmonotonicadjustableresolution
'time'GetSystemTimeAsFileTime()FalseTrue0.015625
'thread_time'GetThreadTimes()TrueFalse1e-07
'process_time'GetProcessTimes()TrueFalse1e-07
'monotonic'GetTickCount64()TrueFalse0.015625
'perf_counter'QueryPerformanceCounter()TrueFalse1e-07

Where,

  • Adjuable is True if the clock can be changed automatically or manually by the system administrator, otherwise it is False.
  • Impementation represents the name of the underlying C function used to obtain the clock value.
  • If the clock cannot go backwards, monotonic is True, otherwise it is False.
  • Resolution represents the clock resolution in seconds.

Next, you can test the characteristics of these clocks.

>>> def test(n):
...   aTime = time.time()
...   aTh = time.thread_time()
...   aPr = time.process_time()
...   aMo = time.monotonic()
...   aPe = time.perf_counter()
...   for i in range(int(n)): j = i**2
...   bTime = time.time()
...   bTh = time.thread_time()
...   bPr = time.process_time()
...   bMo = time.monotonic()
...   bPe = time.perf_counter()
...   aStr = f'aTime={aTime},aTh={aTh},aPr={aPr},aMo={aMo},aPe={aPe}\n'
...   bStr = f'bTime={bTime},bTh={bTh},bPr={bPr},bMo={bMo},bPe={bPe}'
...   print(aStr+bStr)
...
>>> test(1e6)
aTime=1634625786.136904,aTh=0.03125,aPr=0.03125,aMo=199082.078,aPe=199085.4751224
bTime=1634625786.340363,bTh=0.234375,bPr=0.234375,bMo=199082.281,bPe=199085.6787309
>>> test(1e6)
aTime=1634625789.7817287,aTh=0.234375,aPr=0.234375,aMo=199085.734,aPe=199089.1195357
bTime=1634625789.981198,bTh=0.421875,bPr=0.421875,bMo=199085.921,bPe=199089.3195721
>>> test(1e6)
aTime=1634625796.3934195,aTh=0.421875,aPr=0.421875,aMo=199092.343,aPe=199095.731209
bTime=1634625796.5789576,bTh=0.609375,bPr=0.609375,bMo=199092.531,bPe=199095.9172852
>>>

You can clearly see that in the interval between calls to test, thread_time and process_ The time does not change, that is, they do not calculate the time a thread or process sleeps.

Generally, in the time module, the two most commonly used functions are time.time() and time.sleep(), which are used to get the time stamp to count the running time of the program. The latter suspends the thread.

You can use time.thread_time() to detect the function of the sleep function

>>> def test(n):
...    aTime = time.time()
...    aTh = time.thread_time()
...    aPr = time.process_time()
...    time.sleep(n)
...    bTime = time.time()
...    bTh = time.thread_time()
...    bPr = time.process_time()
...    aStr = f'aTime={aTime},aTh={aTh},aPr={aPr}\n'
...    bStr = f'bTime={bTime},bTh={bTh},bPr={bPr}'
...    print(aStr+bStr)
...
>>> test(1)
aTime=1634649370.2819958,aTh=0.640625,aPr=0.640625
bTime=1634649371.2862759,bTh=0.640625,bPr=0.640625
>>> test(1)
aTime=1634649372.72013,aTh=0.640625,aPr=0.640625
bTime=1634649373.723695,bTh=0.640625,bPr=0.640625
>>> test(1)

timezone

Next, you need to introduce some concepts about time

  • GMT: Greenwich Mean Time.
  • UTC: World Coordinated Time, more accurate than Greenwich.
  • DST:D is Daylight and represents daylight saving time.
  • CST: Standard time in the United States, Australia, China, Cuba.

Once you know the concepts of these time zones, you can understand the constants in time:

constantaltzonedaylighttznametimezone
Time zone offset0 if no DST time zone is definedTime Zone NameLocal Time Zone Offset

struct_time

To better represent time, struct_is encapsulated in time Time class whose members include

IndexesattributevalueMeaning
0tm_yearpositive integeryear
1tm_monrange [1, 12]month
2tm_mdayrange [1, 31]Date in month
3tm_hourrange [0, 23]time
4tm_minrange [0, 59]branch
5tm_secrange [0, 61]second
6tm_wdayrange [0, 6], Monday is 0Week is coming
7tm_ydayrange [1, 366]The day of the year
8tm_isdst0, 1 or -1Is DST
-tm_zoneAbbreviation of time zone name
-tm_gmtoffUTC deviation eastward in seconds

Understanding struct_ With time as the data structure, you can read the following functions.

Single parameter function
gmtime(secs)Convert timestamp to UTC time [struct_time format]
localtime(secs)Convert stamp to local time [struct_time format]
ctime(secs)Convert timestamp to UTC time string
asctime(secs)Converting a time structure to a local time string
mktimeInverse of localtime, struct_time to seconds

time.strftime(format[, t])

You can struct_time is formatted by a matcher and converted to

NameMeaningNameMeaning
%aAbbreviation of week%AName of week
%bAbbreviation of month%BMonth Name
%cAppropriate date and time representation
%dMid-month, range [01,31]%jMid-year, range [001,366]
%HHours, range [00,23]%IHours, Range [01,12]
%MMinutes, range [00,59]%SSeconds, range [00,61]
%pAM or PM
%mMonth, range [01,12]
%UWeeks in the year, range [00,53]
Sunday as the first day
%WMonday as first day, same as left
%wMidday of Week, Range [0 (Sunday), 6]
%xAppropriate date representation%XAppropriate time representation
%yCentury-free years, range [00,99]%YCentury Year
%zTime zone offset
%ZTime Zone Name
%%Literal'%'character.

strptime() is its inverse function.

for example

>>> t = time.strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
>>> t
'Tue, 19 Oct 2021 13:46:37 +0000'
>>> T = time.strptime(t,"%a, %d %b %Y %H:%M:%S +0000")
>>> T
time.struct_time(tm_year=2021, tm_mon=10, tm_mday=19, tm_hour=13, tm_min=46, tm_sec=37, tm_wday=1, tm_yday=292, tm_isdst=-1)

Posted by jguy on Tue, 19 Oct 2021 10:08:58 -0700