How to find the system time in Python
Table of Contents
This article seeks to help you find the time at a given point of the system in Python. We will engage the use of python modules to help us realize this.
But why do we need a system time?
Using the current system time is vital for various reasons, ranging from monitoring a program’s performance, information on the network, debugging, and handling random number seeds.
We will break down various approaches to getting the current time of your desired system. These approaches include:
- time module
- datetime module
Before we begin, you need to understand the various ways you can test the concepts herein. The first case is running the code directly on the python terminal. The second approach puts the same code in a script that ends in .py and uses python to trigger it. For instance, if my script is in a file called date_time.py, then I will initiate the process by opening a terminal if you are on Linux or Ubuntu and CMD on windows. Then, navigate to the location of the script. Subsequently, run your script, as shown below.
if you are not using python 3.0 +
All our demonstrations will use the first approach, where we run the code on a python terminal. To have a similar working environment, open the terminal and run the command python3 or python depending on the python version. You should get a window similar to the one below. If you do, then you are ready. Thumbs up!!
Using the Time Module to find the System’s current Time
- importing the time module
- calling the localtime()
- storing the output in a variable, system_time
-display the system time
import time print(time.time()) current_system_time = time.localtime(time.time()) print("current system time :", current_system_time )
In the output above, the resultant output of time.time() refers to the count of seconds passed from 1 January 1970.
On the other end, the output from localtime() is not intuitive and needs to be formatted to easily read and understand. The subsequent section seeks to help you present the latter time in a format that is easily understandable.
import time # approach one current_system_time_1 = time.asctime(time.localtime(time.time())) print("n Output from Asctime function: ", current_system_time_1) # approach two current_system_time_2 = time.ctime(time.time()) print("n Output from Ctime function :", current_system_time_2)
Using the datetime Module to Find the Current System Time
Next, we demonstrate how to find the current system time using the datetime module using examples. datetime module does not require you to install it externally because it is built into Python. Also, note that the datetime module works for dates and time.
- import the module, datetime
- call the datetime now() method as follows
the returned system time is then stored in a variable called current_system_time as follows
current_system_time = datetime .datetime.now()
- Display the final results as shown
print(“The current System Time :”, current_system_time )
complete code that uses datetime module to find the current system time
Example 1: The current System Time
import datetime current_system_time = datetime.datetime.now() print("The current System Time :", current_system_time )
According to the output shown above, the current system time appears in the format of YYY-HH-MM-MS.
Note that we can modify the above output to different formats that suit our needs. The module datetime has this capability, and we will illustrate this below.
import datetime current_system_time= datetime.datetime.now() print("nCurrent System Time : ", current_system_time ) print(current_system_time .strftime("nHH(12H)-MM-SS-PM/AM %I:%M:%S %p")+"n") print(current_system_time .strftime("YYYY-MM-DD-%Y-%m-%d HH-MM-SS-%H:%M:%S")+"n") print(current_system_time .strftime("Day = %a,Month = %b, Date = %d,Year = %Y")+"n") print(current_system_time .strftime("HH-MM-SS %H:%M:%S")+"n") print(current_system_time .strftime("YYYY-MM-DD %Y/%m/%d")+"n")
Getting Different Date Time Attributes
There is the various date and time attributes available at your disposal. These include getting the date, year or month of the current date. To help you master this, we have an illustration below.
import datetime current_system_time = datetime.datetime.now() print ("nMicrosecond is: %d" % current_system_time.microsecond) print ("Second is: %d" % current_system_time.second) print ("Minute is: %d" % current_system_time.minute) print ("Hour is: %d" % current_system_time.hour) print ("Day is: %d" % current_system_time.day) print ("Month is: %d" % current_system_time.month) print ("Year is: %d" % current_system_time.year)
Example 2: formatting the date today
from datetime import date date_today = date.today() print("The date today is :", date_today )
The datetime module has diverse options to enable us to format the date today in the way that best suits our scenario. Let’s use the example above to illustrate this.
import datetime date_time = datetime.datetime.now() print ("nThe current date and time is = %s" % date_time) print ("nThe time now is : = %s:%s:%s" % (date_time.hour, date_time.minute, date_time.second)) print ("nThe date today is: = %s/%s/%s" % (date_time.day, date_time.month, date_time.year) +"n")
How to get time for a specific timezone:
The method now() in the datetime module takes timezone as the input to output the time for the specified timezone. We will use the pytz library to define the different timezones.
If you do not have the pytz library already installed in your system, we recommend doing so. The easiest way to install pytz library in ubuntu or any Debian distro for that matter is:
[email protected]:~$ pip3 install pytz
Just ensure that you have pip3 also installed. In case you do not have it, run the following command.
[email protected]:~$ sudo apt-get install python3-pip
Example of using pytz to show the current system time for different timezones
# Example 1 import datetime import pytz # get current time using now() current_system_time = datetime.datetime.now(pytz.timezone('US/Eastern')) print ("The current system time in US is : ") print (current_system_time )
# Example 2 import datetime import pytz # specify timezone london_time_zone = pytz.timezone('Europe/London') # get current time using now() london_date_time = datetime.datetime.now(london_time_zone ) print("Time Now in London: ", london_date_time.strftime("%H:%M:%S"))
How to Convert Timestamps to Date and Time
Timestamps are mostly used in databases, protocols and applications. These timestamps follow the computer system way of representing time. The latter relies on the count of seconds since 1st January 1970. The Unix epoch has the format 00:00:00 UTC.
We use the time library to generate the current system timestamp and illustrate how you get dates and time from the timestamp, as shown below.
import time print(time.time())
We will then use the datetime function fromtimestamp() to convert timestamp to a datetime object as follows:
import time from datetime import datetime my_timestamp= time.time() print(datetime.fromtimestamp(my_timestamp))
import time from datetime import datetime, timezone my_timestamp= time.time() print(datetime.fromtimestamp(my_timestamp, timezone.utc))
How to convert Date and Time to Timestamps
timestamp() function is crucial when you need to convert a datetime object to a timestamp. The example below illustrates how you can achieve this simply.
from datetime import timezone, datetime date_time_object= datetime.now(timezone.utc) print("n Before conversion : datetime object n") print(date_time_object) print("n After conversion: Timestamp n") print(date_time_object.timestamp())
The article has been all about finding the various ways of getting the current system time in Python and the various dynamic approaches to format it to suit our needs, and the varied scenarios we face day-in-day-out.
In case you have a different approach from what we have shared, we would be glad to accommodate it.