English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn how to get the current time of the language environment and different time zones in Python.
You can use various methods to get the current time in Python.
from datetime import datetime now = datetime.now() current_time = now.strftime("%H:%M:%S") print("Current time =", current_time)
In the above example, we fromdatetimeThe datetime module has imported the datetime class. Then, we use the now() method to get the datetime object containing the current date and time.
Then usedatetime.strftime()Method to create a string representing the current time.
If you need to create a time object containing the current time, you can perform the following operation.
from datetime import datetime now = datetime.now().time() # time object print("now =", now) print("type(now) =", type(now))
You can also use the time module to get the current time.
import time t = time.localtime() current_time = time.strftime("%H:%M:%S", t) print(current_time)
If you need to find the current time of a certain time zone, you can usepytz module.
from datetime import datetime import pytz tz_NY = pytz.timezone('America/New_York') datetime_NY = datetime.now(tz_NY) print("New York 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"))