time 模块是Python 中的标准模块。使用 Python 时,包含与时间相关的操作至关重要。
time模块提供了各种与时间相关的函数和方法,可以通过导入time模块来访问:
import time
除非另有说明,时间模块表示自纪元以来的时间(以秒为单位)。这对于 Windows 和大多数 UNIX 系统来说很常见,但是纪元是多少?
了解时代
新纪元时间,也称为 UNIX 时间,表示自 1970 年 1 月 1 日 00:00:00 协调世界时 (UTC) 以来经过的时间(以秒为单位)。
该日期被称为“纪元”,是许多编程语言(包括 Python)中时间开始的共同点。
在Python中,可以表示纪元之前的时间,但通常以纪元以来的秒数表示。这种方法简化了时间的计算和表示。
让我们看一个获取当前时间(自纪元以来的秒数)的示例。
import time
current_time = time.time()
print(current_time)
Output:
1649268400.23
time.time() 函数以浮点数形式返回自纪元以来的当前时间(以秒为单位),但这是否是使用 Python 中的 time 模块表示时间的唯一方法?不。
时间表示
Python 的 time 模块提供了多种表示时间的方法。其中包括时间戳和 struct_time 对象(时间元组)。
时间戳
时间戳是表示时间的最常见方式,以自纪元以来的秒数表示。
import time
current_timestamp = time.time()
print(f"Current timestamp: {current_timestamp}")
Output:
Current timestamp: 1649268400.23
在这个例子中,我们使用time.time()
函数获取当前时间作为时间戳。
struct_time 对象
struct_time 对象由 time 模块中的各种函数返回,例如gmtime()
, localtime()
, and strptime()
。它本质上是一个带有namedtuple接口的时间元组。
import time
current_time_utc = time.gmtime()
print(f"Current UTC time: {current_time_utc}")
Output:
Current UTC time: time.struct_time(tm_year=2023, tm_mon=7, tm_mday=1, tm_hour=8, tm_min=47, tm_sec=30, tm_wday=5, tm_yday=182, tm_isdst=0)
在上面的例子中,time.gmtime()
返回一个struct_time
表示 UTC 当前时间的对象。
时区和 UTC
时区是地球上具有相同标准时间的区域。
他们遵循这样的概念:地球一天 24 小时分为 24 个时区,每个时区的时间都是相同的。
Python time 模块不直接支持时区。
但是,它确实提供了处理夏令时(与时区相关的常见方面)的功能,并允许本地时间和协调世界时间 (UTC) 之间的转换。
时区通常定义为与 UTC 的偏移量.
例如,美国中部时区标准时间为 UTC-6 小时,夏令时为 UTC-5 小时。
在 Python 中处理时间时,了解时区至关重要,尤其是当您的应用程序需要处理不同区域的日期和时间时。
对于更高级的日期和时间操作,包括全面的时区处理,您可能需要考虑使用 datetime 和 pytz 模块。
打破时间结构
struct_time 或时间元组结构由 9 个字段组成,每个字段代表日期和时间的不同组成部分。
让我们用一个例子来分解这个结构:
import time
current_time = time.localtime()
print(f"Current time structure: {current_time}")
Output:
Current time structure: time.struct_time(tm_year=2023, tm_mon=7, tm_mday=1, tm_hour=10, tm_min=47, tm_sec=30, tm_wday=5, tm_yday=182, tm_isdst=1)
在上面的例子中,time.localtime()
函数返回一个struct_time
表示当前本地时间的对象。该对象包含以下元素:
-
tm_year
:年份,例如2023 年。
-
tm_mon
:一年中的月份,范围从 1(一月)到 12(十二月)。
-
tm_mday
:一个月中的第几天,范围从 1 到 31。
-
tm_hour
:一天中的小时,范围从 0 到 23。
-
tm_min
:一小时中的分钟,范围为 0 到 59。
-
tm_sec
:分钟的秒数,通常范围为 0 到 59,但最大可达 61,其中 60 表示闰秒,由于历史原因支持 61。
-
tm_wday
:一周中的某一天,其中星期一为 0,星期日为 6。
-
tm_yday
:一年中的第几天,范围从 1 到 366。
-
tm_isdst
:指示夏令时 (DST) 是否有效的标志。当 DST 有效时,该值为 1;当 DST 无效时,该值为 0;当 DST 未知时,该值为 -1。
使用夏令时
夏令时 (DST) 是在一年中较温暖的时期将时钟调快一小时的做法,这样晚上的日照时间会更长,而早晨的日照时间会更少。
Python time 模块提供了tm_isdst
标志在struct_time
指示 DST 是否生效的对象。
值 0 表示 DST 未生效,1 表示 DST 生效,-1 表示 DST 未知。
该标志由类似的函数设置localtime()
and gmtime()
当它们被无参数调用时,并且它被使用mktime()
确定 DST 在指定时间是否生效。
这是一个例子:
import time
local_time = time.localtime()
print(f"DST flag: {local_time.tm_isdst}")
Output:
DST flag: 1
在此示例中,我们使用以下方法检索当前本地时间time.localtime()
,然后打印tm_isdst
旗帜。结果为 1 表示 DST 当前生效。
Python 时间模块基本功能
Python Time 模块提供了一系列函数,有助于在 Python 程序中执行和管理与时间相关的任务。
这些函数可用于各种目的,例如获取当前时间、在不同格式之间转换时间、获取 UTC 时间、延迟程序的执行以及测量代码的效率。
time() 函数
The time()
函数返回自纪元以来的当前时间(以秒为单位),这是一个浮点值,表示自纪元以来经过的总秒数。
以下是如何使用它的示例:
import time
current_time = time.time()
print(f"Current time in seconds since epoch: {current_time}")
Output:
Current time in seconds since epoch: 1649268400.23
在此代码片段中,time.time()
函数返回自纪元以来的当前时间(以秒为单位)。
该值表示自纪元以来经过的秒数。这是一种以允许简单计算的格式跟踪时间的简单方法,例如计算两个时间之间的差异。
ctime() 函数
The ctime()
函数用于获取当前时间的字符串表示形式,格式如下:“Wed Dec 31 17:46:40 2023”。返回的字符串以可读格式表示本地时间。
让我们看看它的实际效果:
import time
current_time = time.ctime()
print(f"Current time string: {current_time}")
Output:
Current time string: Sat Jul 1 10:47:30 2023
在上面的代码中,time.ctime()
返回表示当前时间的字符串。该字符串的格式如下:星期几、月、日、时:分:秒、年。
asctime() 函数
The asctime()
函数将自纪元以来以秒为单位的时间或时间元组转换为表示本地时间的字符串。
如果未提供参数,则需要当前时间。
这是一个使用示例asctime()
与当前时间:
import time
current_time = time.asctime()
print(f"Current time string: {current_time}")
Output:
Current time string: Sat Jul 1 10:47:30 2023
在这段代码中,time.asctime()
返回表示当前时间的字符串,格式为:星期几、月、日、时:分:秒、年。
The asctime()
函数还可以用于将时间元组转换为字符串:
import time
t = (2023, 7, 1, 10, 47, 30, 5, 182, 1)
time_string = time.asctime(t)
print(f"Time string: {time_string}")
Output:
Time string: Sat Jul 1 10:47:30 2023
在这段代码中,time.asctime()
接受一个时间元组并返回一个表示该时间的字符串。元组的结构是(年、月、日、时、分、秒、星期几、一年中的某一天、夏令时标志)。
sleep() 函数
The sleep()
函数用于将 Python 程序的执行暂停给定的秒数。
下面是它的使用示例:
import time
print("Start : %s" % time.ctime())
time.sleep(5)
print("End : %s" % time.ctime())
Output:
Start : Sat Jul 1 10:47:30 2023
End : Sat Jul 1 10:47:35 2023
在上面的代码中,我们使用以下命令打印当前时间time.ctime()
,使用暂停执行 5 秒time.sleep(5)
,然后再次打印当前时间。
两次打印的时间相差正好5秒。
此函数在许多场景中都很方便,例如当您想要延迟执行下一行代码、在程序中模拟延迟或在循环中的函数调用之间创建间隔时。
gmtime() 函数
The gmtime()
函数返回协调世界时 (UTC) 中的当前时间,也称为格林威治标准时间 (GMT)。
该函数返回一个struct_time
对象以自纪元以来的秒数表示,其中所有字段均按 UTC 计算。
以下是如何使用的示例gmtime()
功能:
import time
current_time_utc = time.gmtime()
print(f"Current UTC time: {current_time_utc}")
Output:
Current UTC time: time.struct_time(tm_year=2023, tm_mon=7, tm_mday=1, tm_hour=8, tm_min=47, tm_sec=30, tm_wday=5, tm_yday=182, tm_isdst=0)
在上面的代码中,time.gmtime()
返回 UTC 格式的 struct_time 对象。此输出显示年、月、日、小时、分钟和秒,全部采用 UTC 格式。
这次不考虑夏令时tm_isdst
is 0.
The gmtime()
当您需要使用或显示 UTC 时间时,该函数非常有用,这对于用户位于不同时区的应用程序特别有用。
本地时间()函数
The localtime()
函数用于将自纪元以来以秒为单位的时间转换为struct_time
在当地时间。
如果没有提供参数,它将返回当前本地时间。
以下是您可以如何使用localtime()
功能:
import time
local_time = time.localtime()
print(f"Local current time: {local_time}")
Output:
Local current time: time.struct_time(tm_year=2023, tm_mon=7, tm_mday=1, tm_hour=10, tm_min=47, tm_sec=30, tm_wday=5, tm_yday=182, tm_isdst=1)
在此代码片段中,time.localtime()
返回表示当前本地时间的 struct_time 对象。
当您需要根据系统本地设置获取当前时间时,此功能非常有用。
mktime() 函数
The mktime()
函数用于将本地时间的时间元组转换为自纪元以来的秒数。
该函数接受一个时间元组并返回一个浮点数,表示自纪元以来经过的秒数。
这是一个使用示例mktime()
:
import time
t = (2023, 7, 1, 10, 47, 30, 5, 182, 1)
seconds = time.mktime(t)
print(f"Time in seconds since epoch: {seconds}")
Output:
Time in seconds since epoch: 1691083650.0
在上面的例子中,time.mktime()
接受一个时间元组并返回自纪元以来的相应时间(以秒为单位)。
The mktime()
当您需要执行计算或与其他时间戳进行比较时,该函数非常有用。
strftime() 函数
The strftime()
函数根据特定格式将时间元组转换为字符串。
格式由格式字符串定义,其中不同的格式代码代表日期和时间的不同部分。
以下是您可以如何使用strftime()
功能:
import time
t = time.localtime()
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", t)
print(f"Formatted time: {formatted_time}")
Output:
Formatted time: 2023-07-01 10:47:30
在上面的代码中,time.strftime()
有两个参数:格式字符串和时间元组。
格式字符串包含格式代码,它们是日期和时间部分的占位符。
在这种情况下,“%Y-%m-%d %H:%M:%S”表示年-月-日时:分:秒。
The strftime()
函数根据一组格式代码将时间格式化为字符串。
下面是一些常用格式代码的表格strftime()
:
Directive |
Meaning |
%a |
Weekday as locale’s abbreviated name. |
%A |
Weekday as locale’s full name. |
%w |
Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. |
%d |
Day of the month as a zero-padded decimal number. |
%b |
Month as locale’s abbreviated name. |
%B |
Month as locale’s full name. |
%m |
Month as a zero-padded decimal number. |
%y |
Year without century as a zero-padded decimal number. |
%Y |
Year with century as a decimal number. |
%H |
Hour (24-hour clock) as a zero-padded decimal number. |
%I |
Hour (12-hour clock) as a zero-padded decimal number. |
%p |
Locale’s equivalent of either AM or PM. |
%M |
Minute as a zero-padded decimal number. |
%S |
Second as a zero-padded decimal number. |
%f |
Microsecond as a decimal number, zero-padded on the left. |
%z |
UTC offset in the form +HHMM or -HHMM. |
%Z |
Time zone name. |
%j |
Day of the year as a zero-padded decimal number. |
%U |
Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. |
%W |
Week number of the year (Monday as the first day of the week) as a zero padded decimal number. |
strptime() 函数
The strptime()
函数将表示时间的字符串按照特定格式转换为struct_time
.
时间字符串需要采用格式代码定义的格式。
这是如何使用的示例strptime()
功能:
import time
time_string = "2023-07-01 10:47:30"
t = time.strptime(time_string, "%Y-%m-%d %H:%M:%S")
print(f"Time tuple: {t}")
Output:
Time tuple: time.struct_time(tm_year=2023, tm_mon=7, tm_mday=1, tm_hour=10, tm_min=47, tm_sec=30, tm_wday=5, tm_yday=182, tm_isdst=-1)
在这个例子中,time.strptime()
将时间字符串转换为struct_time
,基于给定的格式代码。
时间字符串“2023-07-01 10:47:30”对应格式代码“%Y-%m-%d %H:%M:%S”,表示年-月-日时:分:秒。
请注意,strptime()
函数接受与以下相同的格式指令strftime()
功能。
perf_counter() 函数
The perf_counter()
函数提供性能计数器的当前值,这是一个具有最高可用分辨率的时钟,用于测量短持续时间。
它确实包括睡眠期间经过的时间并且是整个系统的。
让我们考虑一个例子perf_counter()
可以用来计算执行一段代码所花费的时间:
import time
start_time = time.perf_counter()
# code execution
for i in range(1000000):
pass
end_time = time.perf_counter()
elapsed_time = end_time - start_time
print(f"Elapsed time: {elapsed_time} seconds")
Output:
Elapsed time: 0.07634560000003452 seconds
在这个例子中,time.perf_counter()
在执行 for 循环之前和之后使用。
perf_counter 测量经过的时间,即结束时间和开始时间之间的差值,包括等待时间,例如延迟或 I/O 等待.
确切的时间输出可能会根据系统的性能而有所不同。
perf_counter_ns() 函数
为了获得更高的精度,您可以使用perf_counter_ns()
其行为类似于perf_counter()
,但它以纳秒整数形式返回时间。
import time
start_perf = time.perf_counter_ns()
for i in range(1000000):
pass
end_perf = time.perf_counter_ns()
elapsed_time = end_perf - start_perf
print(f"Elapsed time using perf_counter_ns: {end_perf - start_perf} nanoseconds")
Output:
Elapsed time using perf_counter_ns: 28892300 nanoseconds
process_time() 函数
The process_time()
函数返回当前进程的系统和用户 CPU 时间之和的值(以秒为单位)。
它不包括睡眠期间经过的时间。这对于分析 Python 代码.
让我们看一个如何使用的例子process_time()
测量代码执行的 CPU 时间:
import time
start_time = time.process_time()
# code execution
for i in range(1000000):
pass
end_time = time.process_time()
cpu_time = end_time - start_time
print(f"CPU time: {cpu_time} seconds")
Output:
CPU time: 0.07189000000003485 seconds
在这个例子中,time.process_time()
在循环执行之前和之后调用。
process_time 函数测量 CPU 时间作为结束时间和开始时间之间的差值,不包括等待时间。精确的时间输出可能会根据系统的性能而有所不同。
process_time_ns() 函数
为了获得更高的精度,您可以使用process_time_ns()
函数的行为类似于process_time()
,但它以纳秒整数形式返回时间。
import time
start_proc = time.process_time_ns()
for i in range(1000000):
pass
end_proc = time.process_time_ns()
cpu_time = end_proc - start_proc
print(f"CPU process time using process_time_ns: {end_proc - start_proc} nanoseconds")
Output:
CPU process time using process_time_ns: 31250000 nanoseconds
Python 时间掌握
对我来说,使用time
模块已融入我的编码例程中。它的用处比你想象的要多,而且我仍然记得一个很大程度上依赖于它的使用的特定项目。
我们的客户是一家全球物流公司,他们面临着一个严重的问题。他们每小时有数千笔交易,所有交易都发生在不同的时区。
他们需要一个系统来准确记录和报告这些交易的时间,并考虑到所涉及的不同时区。
他们现有的系统无法胜任这项任务,这就是我和我的团队发挥作用的地方。
我记得一开始是导入time
and pytz
模块,pytz
是一个第三方库,允许精确的跨平台时区计算。
import time
from pytz import timezone
我们决定首先创建一个函数,该函数将 Unix 时间戳和时区作为输入并返回该时区的本地时间。
def convert_to_local_time(unix_timestamp, tz):
tz = timezone(tz)
local_time = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(unix_timestamp))
return tz.localize(local_time)
该函数首先会使用time.gmtime()
将 Unix 时间戳转换为 GMT,然后使用以下命令将其本地化为给定时区tz.localize()
。它工作得很好。
然后是第二个需求:他们想要计算两个时间戳之间经过的时间。听起来很简单,但这并不是一个小问题,因为需要考虑时区和夏令时。
所以,我使用创建了另一个函数time
module.
def time_difference(timestamp1, timestamp2, tz):
t1 = convert_to_local_time(timestamp1, tz)
t2 = convert_to_local_time(timestamp2, tz)
# calculate the difference in seconds
diff = abs(t2 - t1).total_seconds()
return diff
在这里,我首先将两个时间戳都转换为本地时区,然后使用.total_seconds()
timedelta 对象的方法通过将两个 datetime 对象相减来计算以秒为单位的差值。
有了这两个功能,我们就有了很好的基础。但这还不够。
为了充分满足客户的需求,我们必须围绕这些功能构建一个完整的系统,能够每小时处理数千笔交易,并以清晰、易于理解的格式显示这些信息。
但正如他们所说,那是另一回事了。现在,只需说time
模块是我们解决方案的核心。
进一步阅读
https://docs.python.org/3/library/time.html