原文: https://www.programiz.com/python-programming/datetime/current-time
在本文中,您将学习获取语言环境的当前时间以及 Python 中的不同时区。
您可以采用多种方法获取 Python 当前时间。
示例 1:使用datetime对象的当前时间
from datetime import datetimenow = datetime.now()current_time = now.strftime("%H:%M:%S")print("Current Time =", current_time)
在上面的示例中,我们从日期时间模块中导入了datetime类。 然后,我们使用now()方法获取包含当前日期和时间的datetime对象。
然后,使用datetime.strftime()方法,创建一个表示当前时间的字符串。
如果您需要创建一个包含当前时间的time对象,则可以执行以下操作。
from datetime import datetimenow = datetime.now().time() # time objectprint("now =", now)print("type(now) =", type(now))
示例 2:使用时间模块的当前时间
您还可以使用时间模块获取当前时间。
import timet = time.localtime()current_time = time.strftime("%H:%M:%S", t)print(current_time)
示例 3:时区的当前时间
如果需要查找某个时区的当前时间,可以使用pytz模块。
from datetime import datetimeimport pytztz_NY = pytz.timezone('America/New_York')datetime_NY = datetime.now(tz_NY)print("NY time:", datetime_NY.strftime("%H:%M:%S"))tz_London = pytz.timezone('Europe/London')datetime_London = datetime.now(tz_London)print("London time:", datetime_London.strftime("%H:%M:%S"))
