Python 时间模块:使用指南
作者: 社区 / 开发者
2023 年 3 月 24 日
导航至
这篇文章由 Keshav Malik 撰写。向下滚动查看作者简介。
Python time 模块是一个强大的工具,可以以简单和复杂的方式处理时间和日期,让您轻松操作日期、格式化字符串、计算持续时间等等。
如果您知道如何有效地使用 time 模块,您可以使您的编程任务更加轻松。在本指南中,我们将向您展示如何使用它,并提供日常任务的示例,以便您可以将其应用到您自己的项目中。让我们开始吧!
时间模块入门
Python 中的 time 模块提供了各种与时间相关的方法,供开发人员使用。您无需外部安装它,因为它属于 Python 模块的一部分(类似于其他模块,例如 os)。
time 模块提供了一系列函数,允许用户执行诸如格式化字符串、计算持续时间、处理时区等任务。
真实示例
时间和日期是 Python 编程的基本要素。通过利用各种可用工具,开发人员可以将时间和日期操作用于各种应用程序。以下是一些实际示例
-
调度任务: 借助日历库,开发人员可以构建应用程序,根据特定日期和时间调度任务,例如警报或事件提醒。例如,应用程序可以提醒用户在特定日期之前完成某些活动,或以预定的时间间隔发送电子邮件。
-
银行交易: 开发人员可以使用 Python 的 time 模块来确保处理金融交易时的准确性,例如跟踪付款和存款。这对于任何处理银行和金融的应用程序来说显然很重要。
-
用户输入验证: 当接受日期和时间形式的用户输入时,开发人员通常使用 POSIX 时间戳表示,以便可以使用 Python 中的 'strftime()' 等函数快速轻松地验证它,以检查给定值是否有效。
-
日志记录数据: 在开发程序时,将时间戳与日志数据一起存储也是标准做法。通过提供关于特定时间发生的事情的宝贵上下文,它可以更有效地跟踪整个系统的活动。然后,这些数据可用于查找用户行为模式、更快地识别错误,甚至实施预测分析以根据过去的趋势预测结果。
-
游戏开发: 许多游戏需要准确表示时间值,用于各个方面,例如重生计时器、加载动画和地图轮换。所有这些元素通常都使用时间戳进行编码,以在实时场景中平稳运行。同样,简单的计时机制(如倒计时时钟)在游戏过程中通常是必要的,以增加紧张感并创造更动态的游戏体验,而无需每次游戏因服务器问题或其他复杂情况而重新启动时手动重置计时器。
Python 中的时间值
Python 中的时间值通常表示为自 Unix 纪元以来经过的秒数,Unix 纪元是 1970 年 1 月 1 日(00:00:00 UTC)开始的日期和时间参考点。
这些时间戳代表了计算机系统中跟踪时间的全球标准。通过此系统,任何给定时刻都可以使用简单的整数值表示,从而可以轻松比较不同的时间点。
获取当前时间和日期
使用 time() 方法,开发人员可以获取自纪元以来的当前时间(以秒为单位)。
import time
current_time = time.time()
print(f"Current time (in seconds): {current_time}")
current_utc_time = time.gmtime()
print(f"Current UTC time: {current_utc_time}")
开发人员还可以使用 strftime 时间函数创建更友好的日期和时间。我们将在后面的章节中讨论此函数。
import time
# Current time in seconds since the epoch
current_time = time.time()
# Convert the current time to a time tuple
current_time_tuple = time.localtime(current_time)
# Get the current date as a string in the format "MM/DD/YYYY"
current_date = time.strftime("%m/%d/%Y", current_time_tuple)
current_time_string = time.strftime("%H:%M:%S", current_time_tuple)
print("The current time is", current_time_string)
print("Today's date is", current_date)
使用 time 模块获取当前星期几
您还可以使用 time 模块找出今天是星期几,但这有点复杂。
import time
# Get the current time in seconds since the epoch
current_time = time.time()
# Convert the current time to a time tuple
current_time_tuple = time.localtime(current_time)
# Get the current day of the week as an integer (Monday is 0 and Sunday is 6)
current_day = current_time_tuple.tm_wday
# Convert the integer to the corresponding weekday name
weekday_names = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
current_weekday_name = weekday_names[current_day]
print("Today is", current_weekday_name)
最佳方法是使用 datetime 模块。
import datetime
current_date = datetime.datetime.now()
current_day = current_date.strftime("%A")
print("Today is", current_day)
理解时间格式化
Python 中的 time 模块提供了几个函数,可以将时间值格式化为字符串。最常用的函数是 strftime(),它是“string format time”(字符串格式化时间)的缩写。
strftime 函数允许开发人员将时间戳转换为不同的格式,以便于存储和显示。此函数接受两个参数:格式字符串和您希望转换的时间戳值(以 UTC/GMT 时间表示)。
import time
current_time = time.localtime()
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", current_time)
print(formatted_time)
以下是这些符号(%Y、%m 等)的含义
-
%Y:带世纪的年份,以十进制数表示(例如,2023)
-
%m:月份,以零填充的十进制数表示(例如,02 表示二月)
-
%d:月份中的日期,以零填充的十进制数表示(例如,18)
-
%H:小时(24 小时制),以零填充的十进制数表示(例如,08 表示上午 8:00)
-
%M:分钟,以零填充的十进制数表示(例如,30)
-
%S:秒,以零填充的十进制数表示(例如,45)
解析日期/时间字符串
到目前为止,我们只介绍了在您自己的程序中处理、创建和格式化字符串,但在某些情况下,您将从外部来源获取时间数据。例如,您可以使用集成 API,该 API 每分钟向您发送天气数据。API 响应可能包含时间戳。如果是这样,您必须先解析时间戳,然后才能在应用程序中使用它。time 模块提供了 strptime() 函数,它可以将日期/时间字符串解析为时间元组。
以下代码片段显示了此函数的工作方式。
import time
# Dummy weather data as a dictionary with a 'time' key
weather_data = {
'temperature': 25,
'humidity': 80,
'pressure': 1013,
'time': '2022-05-15 14:30:00'
}
# Parse the date/time string into a time tuple using strptime
time_tuple = time.strptime(weather_data['time'], "%Y-%m-%d %H:%M:%S")
# Print the parsed time tuple
print(time_tuple)
上面的代码打印一个时间元组,其中包含日期和时间的各个组成部分,例如年、月、日、小时、分钟和秒。您可以使用此数据执行各种操作,例如日期/时间算术和比较。
测量时间间隔
在 Python 中测量时间间隔涉及计算两个给定时间点之间的差值。当您创建调度应用程序、跟踪用户行为和分析性能数据时,这非常重要。要测量两个特定时间点之间的时间间隔,time 模块提供了一组函数和模块,您可以一起使用它们来实现此结果。
import time
# Record the start time
start_time = time.time()
# Perform some time-consuming operation (Sleep for example)
time.sleep(2)
# Record the end time
end_time = time.time()
# Calculate the elapsed time
elapsed_time = end_time - start_time
print("Elapsed time: {:.2f} seconds".format(elapsed_time)) # Elapsed time: 2.01 seconds
如果您需要更准确的结果,您可以始终使用 perf_counter() 函数。在大多数系统上,此函数返回一个浮点值,表示时间(以秒为单位),精度高于 time()。这是一个示例
import time
# Record the start time
start_time = time.perf_counter()
# Perform some time-consuming operation
time.sleep(2)
# Record the end time
end_time = time.perf_counter()
# Calculate the elapsed time
elapsed_time = end_time - start_time
print("Elapsed time: {:.6f} seconds".format(elapsed_time)) # Elapsed time: 2.005048 seconds
比较时间值
在 Python 中比较时间值可能很棘手,因为没有定义和存储时间值的通用标准。让我们看看如何在 Python 中比较时间值。
将时间值作为字符串进行比较
import time
# Get current time as a string
current_time_str = time.strftime("%H:%M:%S")
# Check if the current time is after 9:00 AM
if current_time_str > "09:00:00":
print("It's after 9:00 AM")
else:
print("It's before 9:00 AM")
将时间值作为秒(自纪元开始以来)进行比较
import time
# Get current time as seconds since the epoch
current_time_sec = time.time()
# Wait for 5 seconds (any random time-consuming task)
time.sleep(5)
# Get current time again
new_time_sec = time.time()
# Calculate the time difference
time_diff = new_time_sec - current_time_sec
# Check if the time difference is at least 5 seconds
if time_diff >= 5:
print("At least 5 seconds have passed")
else:
print("Less than 5 seconds have passed")
结论
对于任何处理日期和时间数据的开发人员来说,Python time 模块都是一个宝贵的资源。本教程介绍了该模块中可用的各种函数,并向您展示了如何使用它。掌握了这些知识,您将拥有构建与日期和时间相关的强大应用程序的工具。无论您是需要测量经过的时间还是对日期执行计算,Python time 模块都将帮助您更轻松地完成这些任务。
关于作者
这篇文章由 Keshav Malik 撰写,他是一位技术精湛且充满热情的安全工程师。Keshav 热衷于自动化、黑客技术以及探索不同的工具和技术。Keshav 热爱寻找解决复杂问题的创新解决方案,并且一直在寻找新的机会来成长和提升自己的专业水平。他致力于保持领先地位,并且始终关注最新和最出色的工具和技术。