Having the knowledge of the ongoing time is useful for creating the timestamps. Timestamp is when a particular incident happened. The value is precise up to the value of milliseconds. The standard time stamp in Python follows the epoch format which refers to the time passed in seconds since January 1970.
Different modules like requests, time, and datatime are available in Python to get the current time. This article discusses different methods to know the present time in Python.
How do I get the Current Time in Python?
Different Python methods like datetime and time can get the present date and time. The time of the particular time zone can also be extracted using these modules. Different methods to get the current time are:
- Using the datetime module
- Using the time module
- Using requests module
Let us discuss each method in detail.
Method 1: Using the datetime Module
The datetime module contains the functionalities that work with the date and time in Python. The datatime module is imported to get its required functionalities.
Let us discuss different examples that use the datetime module to fetch the time.
Example 1: Getting the Present Time
The following examples use the now() method from the datetime module to fetch the current time:
import datetime
cr_time = datetime.datetime.now()
print("The time at the greenwich meridian currently is:", cr_time)
In the above code,
- The datetime module is imported
- The now function is called on the datetime and saved in the variable cr_time that represents the ongoing T me at the Greenwich meridian.
- The current time is printed.
Output
The output displays the present time at the Greenwich meridian using the now() method from the datetime module:
Example 2: Printing the Present Time in ISO Format
The iso format takes the deductive approach when mentioning the date and time which is yyyymmdd. And the time goes from hours to minutes to seconds to the milliseconds. The following code explains how to print the present time in ISO format:
from datetime import datetime as dt
iso_time= dt.now().isoformat()
print("The current time in ISO date format is: ", iso_time)
In the above code,
- The datetime method is imported as dt from the datetime module.
- The iso_time variable stores the current date in ISO format using the method isoformat().
- The current time in ISO format is printed.
Output
The following output displays how to fetch the ongoing date in iso format using the isoformat() method from the datetime module:
Example 3: Using the pytz library
The pytz library provides information about the specified timezone of an area. The third-party module contains precise information about the time zones along with the methods to convert the timezone. The following code shows how pytz library along with the datetime module method can get the present time:
from datetime import datetime
import pytz
timezone= pytz.timezone('Asia/Karachi')
datetime_Karachi = datetime.now(timezone)
print('The current date and time in Karachi is:',datetime_Karachi)
In the above code,
- The datetime method is imported from the datetime module.
- The pytz library is imported which gets the timezone of a specified region
- The timezone method gets the parameter value of ‘Asia/Karachi’ which tells information about the time zone of a specified region which in this case is Karachi.
- The datetime.now method takes the parameter value of the timezone that gives the present date and time of Karachi.
- The values of the present date and time of Karachi are printed.
Output
The following output displays how to get the current date and time of a specified zone using the pytz library:
Example 4: Printing the Present Time in the UTC-datetime Module
The following code explains how to get the present time in the UTC datetime module:
from datetime import datetime as dt
print("The current time in UTC date format is: ", dt.utcnow())
In the above code,
- The datetime method is imported from the datetime module as dt.
- The utcnow() method is called from the datetime module that fetches the ongoing time in the UTC format.
- The date is then printed.
Output
The following output displays how the utcnow() method from the datetime module can fetch the ongoing date and time in the UTC format:
Method 2: Using the time Module
The information about the present time can be extracted by Python’s time module. It contains data regarding the number of seconds that passed since the first of January, 1970. The value is stored in the form of a floating number. This can also be referred to as the Unix approach. As it can represented in the form of integers, it is convenient to use it in various systems with the help of parsing.
Let us discuss different examples that use the time module to get the current time.
Example 1: Method Getting Time in String Format
The strfttime() returns the ongoing time along with the time in the string format. The following code uses the strftime() to extract the data about time in string format:
import time
present_time = time.strftime("%H:%M:%S", time.localtime())
print("The present time is:", present_time)
In the above code,
- The time module is imported.
- The method strftime takes the parameter of %H:%M:%S which indicates that the hours will be printed first then the minutes and seconds. The localtime() function from the time module gets the local time of the user.
- The fetched time is printed in the string format.
Output
The following output displays the functionality of strftime() that gets the ongoing time in string format:
Example 2: Getting the GMT Time
The GMT time is the local time at Greenwich which follows the UTC 0 timezone. The following code explains how to get the time in GMT timezone using gmtime():
import time as tm
gmt_format = tm.gmtime(tm.time())
print('The present time in the GMT format is:\n', gmt_format)
In the above code,
- The time module is imported as tm.
- The variable gmt_format stores the local time in gmt_format using gmtime() with the time() method passed as its parameter value. This converts the current time to the GMT time.
- The present time in the GMT format is printed.
Output
The following output displays the present time in the GMT format using the gmtime() method from the time module:
Example 3: Getting the Time in Milliseconds
The following code explains how the current time can be fetched in milliseconds using the time module:
import time
ms_time = int(round(time.time() * 1000))
print("The time in milliseconds is:", ms_time)
In the above code,
- The time module is imported.
- The variable ms_time stores the current value of time in milliseconds. The int() method converts the millisecond value to the integer value.
- The time in milliseconds is printed.
Output
The following output displays the ongoing time in milliseconds using the time module:
Example 4: Getting the Time in Nanoseconds
The ongoing time can also be printed in nanoseconds using the time_ns() method. The following method explains how to get the time in nanoseconds using the time module:
import time
nano_time= time.time_ns()
print("The current time in nano seconds is:", nano_time)
In the above code,
- The time module is imported.\
- The time_ns() method from the time module is called whose value is stored in the variable nano_time.
- The ongoing time in nanoseconds is printed.
Output
The following output explains how to get the time in nanoseconds using time_ns() from the time module:
Example 5: Getting the Epoch Time
The epoch time refers to the computer’s time. The following code explains how to get the epoch time using the time module:
import time as tm
ep_time = int(tm.time())
print('The present Epoch time:', ep_time)
In the above code,
- The time module is imported astm.
- ™.
- The variable ep_time=int(™.time)) gets the current epoch time.
- The current epoch time is printed.
Output
The following output displays how to get the current epoch time using the time module:
Method 3: Using the requests Module
The Python module requests can be used to extract information about the present time from the internet. The time API is called to know the present time. The following example uses the requests module to find the present time in Helsinki:
import requests
res = requests.get('http://worldtimeapi.org/api/timezone/Europe/Helsinki')
json_res = res.json()
if 'utc_datetime' in json_res:
present_time = json_res['utc_datetime']
print("The current time of Helsinki is",present_time)
else:
print("No record found.")
In the above code,
- The requests module is imported.
- The request module makes the HTTP GET request to the API that gets the timezone of Helsinki. The server response is stored in the variable res.
- The json() method is called on res which deserializes the JSON content.
- The code then checks if the key ‘utc_datetime’ is present in json_res. The resulting value is stored in present_time.
- If it contains the key, it will print Helsinki’s current time else it will print ‘No record found!’.
Output
The above code will give Helsinki’s present time and date. The following output displays how to use the requests module to get the present date by calling a specified timezone API:
Conclusion
The current time in different formats can be fetched using different methods from the datetime, requests, and time modules in Python. The time of a specified region can be known using the pytz library in Python that gets the timezone of that region. The request module helps to get the information of the current time from the internet by getting the API which represents the timezone of a region. The article discusses different methods to get the current time in various formats using different modules in Python and discusses the relevant examples.