原文:Python Get Current Time,作者:Kolade Chris

在你的网站和应用程序中,你可能希望添加时间戳或检查用户活动时间等功能。

每种编程语言都有处理时间的模块或方法,Python 也不例外。

使用 Python 的 datetimetime 模块,你可以获取当前日期和时间,或特定时区的日期和时间。

在本文中,我将向你展示如何在 Python 中使用 datetimetime 模块获取当前时间。

如何使用 Datetime 模块获取当前时间

快速获取当前日期和时间的第一件事是使用 datetime 模块中的 datetime.now() 函数:

from datetime import datetime
current_date_and_time = datetime.now()

print("The current date and time is", current_date_and_time)

# The current date and time is 2022-07-12 10:22:00.776664

这不仅显示时间,还显示日期。

要提取时间,可以使用 strftime() 函数并传入 ("%H:%M:%S")

  • %H 获取小时
  • %M 获取分钟
  • %S 获取秒数
from datetime import datetime
time_now = datetime.now()
current_time = time_now.strftime("%H:%M:%S")

print("The current date and time is", current_time)

# The current date and time is 10:27:45

你也可以像这样重写代码:

from datetime import datetime
time_now = datetime.now().strftime("%H:%M:%S")

print("The current date and time is", time_now)

# The current date and time is 10:30:37

如何使用 Time 模块获取当前时间

除了 datetime() 模块,time 模块是 Python 中另一种获取当前时间的内置方法。

同样的,你必须先导入 time 模块,然后你可以使用 ctime() 方法获取当前日期和时间。

import time

current_time = time.ctime()
print(current_time)

# Tue Jul 12 10:37:46 2022

要提取当前时间,你还必须使用 strftime() 函数:

import time

current_time = time.strftime("%H:%M:%S")
print("The current time is", current_time)

# The current time is 10:42:32

小结

本文向你展示了两种使用 Python 获取当前时间的方法。

如果你想知道在 timedatetime 模块之间使用哪个,这取决于你想要什么:

  • timedatetime 更精确
  • 如果你不想与夏令时(DST)混淆,请使用 time
  • datetime 有更多可以使用的内置对象,但对时区的支持有限

如果你想使用时区,你应该考虑使用 pytz 模块。

为了了解如何在特定区域获得时间,你可以阅读我写的关于 pytz 模块的文章

继续编码:)