在 Python 中,我们可以通过多种方式获取当前时间。
- 使用
datetime
对象 - 使用
time
模块
使用 datetime 对象获取当前时间
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
输出
Current Time = 07:41:19
在上面的示例中,我们从 datetime 模块导入了 datetime
类。
然后,我们使用 now()
函数获取一个包含当前日期和时间的 datetime
对象。
使用 datetime.strftime() 函数,我们创建了一个表示当前时间的 字符串。
使用 time 模块获取当前时间
在 Python 中,我们还可以使用 time 模块获取当前时间。
import time
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
print(current_time)
输出
07:46:58
获取特定时区的当前时间
如果我们需要查找特定时区的当前时间,可以使用 pytz 模块。
from datetime import datetime
import pytz
# Get the timezone object for New York
tz_NY = pytz.timezone('America/New_York')
# Get the current time in New York
datetime_NY = datetime.now(tz_NY)
# Format the time as a string and print it
print("NY time:", datetime_NY.strftime("%H:%M:%S"))
# Get the timezone object for London
tz_London = pytz.timezone('Europe/London')
# Get the current time in London
datetime_London = datetime.now(tz_London)
# Format the time as a string and print it
print("London time:", datetime_London.strftime("%H:%M:%S"))
输出
NY time: 03:45:16 London time: 08:45:16
这里,我们使用了 pytz
模块来查找特定时区的当前时间。
另请阅读