How to get the current time in python
This article will show you How to get the current time in python. This is useful for you will learn to get the current time of your locale as well as different time zones in python. We will also format the date and time in different formats using strftime(). To get both current date and time datetime. now() function of datetime module is used. This function returns the current local date and time.
There are a number of ways you can take to get the current time in Python.
Current time using datetime object
You can also get the current time using datetime object.
from datetime import datetime now = datetime.now() current_time = now.strftime("%H:%M:%S") print("Get Current Time : " + current_time) Output: Get Current Time : 17:51:59
We have imported datetime class from the datetime module. And, we used the now() method to get a datetime object containing the current date and time. Using datetime.strime() method.
from datetime import datetime now = datetime.now().time() print("Current time : {}".format(now)) print("Type is : {} ".format(type(now))) Output: Current time : 18:24:50.767029 Type is : <type 'datetime.time'>
Current time using time module
You can also get the current time using time module.
import time t = time.localtime() current_time = time.strftime("%H:%M:%S", t) print("Current time : " + current_time) Output: Current time : 18:27:27
Current time of a timezone
If you need to find current time of a certain timezone, you can use pytZ module.
from datetime import datetime import pytz tz_ic = pytz.timezone('Iceland') datetime_NY = datetime.now(tz_ic) print("Iceland time:", datetime_NY.strftime("%H:%M:%S")) tz_la = pytz.timezone('America/Los_Angeles') datetime_NY = datetime.now(tz_la) print("Los Angeles time:", datetime_NY.strftime("%H:%M:%S")) tz_ny = pytz.timezone('America/New_York') datetime_NY = datetime.now(tz_ny) print("New York time:", datetime_NY.strftime("%H:%M:%S")) tz_el = pytz.timezone('Europe/London') datetime_London = datetime.now(tz_el) print("Europe London time:", datetime_London.strftime("%H:%M:%S")) tz_em = pytz.timezone('Europe/Malta') datetime_London = datetime.now(tz_em) print("Europe Malta time:", datetime_London.strftime("%H:%M:%S")) Output: Iceland time: 08:07:19 Los Angeles time: 01:07:19 New York time: 04:07:19 Europe London time: 08:07:19 Europe Malta time: 09:07:19