在本文中,您將學(xué)習獲取語言環(huán)境的當前時間以及Python中的不同時區(qū)。
您可以采用多種方法獲取Python當前時間。
from datetime import datetime now = datetime.now() current_time = now.strftime("%H:%M:%S") print("當前時間 =", current_time)
在上面的示例中,我們從datetime模塊導(dǎo)入了datetime類。然后,我們使用now()方法來獲取datetime包含當前日期和時間的對象。
然后使用datetime.strftime()方法創(chuàng)建一個表示當前時間的字符串。
如果您需要創(chuàng)建一個包含當前時間的time對象,則可以執(zhí)行以下操作。
from datetime import datetime now = datetime.now().time() # time object print("now =", now) print("type(now) =", type(now))
您還可以使用時間模塊獲取當前時間。
import time t = time.localtime() current_time = time.strftime("%H:%M:%S", t) print(current_time)
如果需要查找某個時區(qū)的當前時間,可以使用pytZ模塊。
from datetime import datetime import pytz tz_NY = pytz.timezone('America/New_York') datetime_NY = datetime.now(tz_NY) print("紐約時間:", datetime_NY.strftime("%H:%M:%S")) tz_London = pytz.timezone('Europe/London') datetime_London = datetime.now(tz_London) print("倫敦時間:", datetime_London.strftime("%H:%M:%S"))