There are many ways to get the current time in Python, but the most straightforward and versatile way is to use the now()
method in the built-in datetime
module.
In today’s post, we’ll discuss various ways to use the now()
method to get the current time in Python. We’ll also discuss what a timestamp is and when is it useful to get the current timestamp instead of the current time.
Last but not least, we’ll write a simple function that prompts users to enter messages and stores those messages with the current timestamp in a list.
Table of Contents
How to get current time in Python using the datetime module
The datetime
module is a built-in module in Python that comes with many convenient methods for working with dates and time. To get the current time (and date), we can use the now()
method. This method gives us the current time and date in the local timezone.
Let’s look at some examples:
Using the now() method in Python to get the current time and date
from datetime import datetime current_time = datetime.now() print(current_time)
To use the now()
method, we need to first import the datetime
class using the import
statement on line 1.
Next, we call the now()
method (datetime.now()
) on line 2. This method returns a datetime
object, which we assign to a variable called current_time
.
On line 4, we use the print()
function to print the value of current_time
.
If you run the code above, you’ll get something similar to
2020-10-03 13:24:09.743366
which represents the current date and time at the point when you run the code.
This current date and time is given in the local timezone.
The date is given in the YYYY-MM-DD format while time is given in 24 hour notation. The decimal value (743366) at the end represents microseconds.
Formatting the result of the now() method
When using the now()
method in Python to get the current time and date, it is possible to display the result using a format that is different from what is shown in the output above.
To do that, we need to use the strftime()
method. This method allows us to format a datetime
, date
or time
object by passing a format string to the method.
Let’s look at an example:
from datetime import datetime current_time = datetime.now().strftime('%a %b %d, %Y %I:%M:%S %p') print(current_time)
Here, we first import the datetime
class on line 1.
Next, we call the now()
method and use the result of the now()
method to call the strftime()
method on line 2. We pass the format string '%a %b %d, %Y %I:%M:%S %p'
to the method.
Notice the symbols %a, %b etc in the format string? These symbols are known as directives. They tell Python what information we want to display from the now()
method and how the information should be displayed.
%a tells Python to display the day of week in abbreviated form (e.g. Mon, Tue, … Sun)
%b tells Python to display the abbreviated month (e.g. Jan, Feb,… Dec)
%d tells Python to display the day of the month as a zero-padded decimal number (e.g. 01, 02, …, 31) and so on.
A full list of all the directives can be found at https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes.
Besides these directives, the format string in our example also includes a comma, spaces and semi-colons. These additional characters will be displayed in the result as well. If you run the code above, you’ll get an output similar to the following:
Sat Oct 03, 2020 01:39:35 PM
Using the now() method to get the current date
The examples above show us how to use the Python now()
method to get the current time and date.
If you only want to get the date (without time), you can use the result of the now()
method to call the date()
method, as shown in the example below:
from datetime import datetime #Get current date current_date = datetime.now().date() print(current_date) #Format current date formatted_date = current_date.strftime('%b %d, %Y') print(formatted_date) #current_date does not contain current time information formatted_date = current_date.strftime('%b %d, %Y %I:%M:%S %p') print(formatted_date)
Here, we use the result of datetime.now()
to call the date()
method on line 4. This gives us a date object, which we assign to a variable called current_date
. Next, we use the print()
function to print the value of current_date
.
On line 8, we use current_date
to call the strftime()
method, passing '%b %d, %Y'
as the format string. This format string gives us the month (%b), day (%d) and year (%Y) of the current date.
Finally, on line 12, we use current_date
to call the strftime()
method again, passing '%b %d, %Y %I:%M:%S %p'
as the format string this time. This format string includes directives for the time (%I, %M, %S and %p).
If you run the code above, you’ll get an output similar to
2020-10-03 Oct 03, 2020 Oct 03, 2020 12:00:00 AM
The last output shows that time information is not provided by the date()
method. Hence, time is displayed as 12:00:00 AM when we try to display the time.
Using the now() method to get the current time
Next, if you are only interested in getting the current time (without the date), you can use the time()
method. Let’s look at an example:
from datetime import datetime #Get current time current_time = datetime.now().time() print(current_time) #Format current time formatted_time = current_time.strftime('%I:%M:%S %p') print(formatted_time) #current_time does not contain current date information formatted_time = current_time.strftime('%b %d, %Y %I:%M:%S %p') print(formatted_time)
The code above should be quite self-explanatory, as the time()
method is very similar to the date()
method.
If you run the code above, you’ll get an output similar to the following:
14:15:09.197119 02:15:09 PM Jan 01, 1900 02:15:09 PM
The last output shows that current date information is not provided by the time()
method. Hence, when we try to display the date (on line 12 in the code above), we get Jan 01, 1900 as the output (which is not the current date).
Setting the timezone used by the now() method
The Python now()
method allows us to specify the timezone to use when getting the current time and date. Else, it uses the local timezone by default.
To specify the timezone, we need to import another module – the pytz
module.
Unfortunately, the pytz
module is not part of the standard Python distribution and needs to be installed separately. If you have not previously installed pytz
, you can refer to the section below for more information on installing the pytz
module.
Once you have successfully installed pytz
, you can use the module to specify a timezone.
We do that using the timezone()
method, by passing the timezone as a string to the method.
For instance, if we want the New York timezone, we pass the string 'America/New_York'
to the method. To find out what timezones can be passed to the method, you can run the following code:
import pytz all_tz = pytz.all_timezones for i in all_tz: print(i)
This gives us a list of all the timezones available. The first few lines of output is shown below:
Africa/Abidjan Africa/Accra Africa/Addis_Ababa Africa/Algiers Africa/Asmara Africa/Asmera
You can also refer to https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a similar list.
After creating the timezone, you can pass this timezone to the now()
method in the datetime
class.
Let’s look at an example:
from datetime import datetime import pytz tz = pytz.timezone('America/New_York') dt_now = datetime.now(tz).strftime('%I:%M:%S %p') print("Current Time in New York =", dt_now) tz = pytz.timezone('Europe/London') dt_now = datetime.now(tz).strftime('%I:%M:%S %p') print("Current Time in London =", dt_now)
Here, we first import the datetime
and pytz
modules on lines 1 and 2.
Next, we pass the string 'America/New_York'
to the pytz.timezone()
method on line 4 and assign the result to a variable called tz
.
We then pass this variable to the now()
method on line 5 to specify the timezone to use.
Next, we print the result on line 6.
From lines 8 to 10, we repeat the same steps, using 'Europe/London'
as the timezone this time.
If you run the code above, you’ll get an output similar to the following:
Current Time in New York = 06:14:59 AM Current Time in London = 11:14:59 AM
Getting timestamp of current time
Now that you are familiar with the now()
method, let’s move on to discuss a related concept – timestamp.
When working with dates and time, sometimes it can be useful to get the current timestamp instead of the current date and time. This is especially true if we have an application that is used by users in different timezones.
Suppose we have two users – April and Ben – using the application in New York and London respectively.
When Ben uses the application in London, we may want to store his log-out time in our database. If we use the now()
method, we may store this time as '5 Oct 2020 11:14:59 AM'
.
When April logs in one minute later and sees that Ben logged out at 5 Oct 2020 11:14:59 AM, she will find it weird as her current time is only 5 Oct 2020 06:15:59 AM, since New York is 5 hours behind London.
In cases like these (where we have users in different timezones), it may be better to use a timestamp instead. A timestamp gives us the numbers of seconds that have elapsed since since Jan 01 1970 (UTC). For instance, at the point of writing, the timestamp is 1601894980. This timestamp is the same regardless of which timezone the user is in, since it is measured from the same point in history (Jan 01 1970 UTC).
To get the current timestamp, we use the built-in time()
method. This method is available in the time
module. Let’s look at an example:
from time import time ts = time() print(ts)
Here, we first import the time
module on line 1.
Next, we call the built-in time()
method to get the timestamp and assign the result to a variable ts
.
Finally, we print the value of ts
on line 4.
If you run the code above, you’ll get an output similar to the following:
1601895993.8131888
The timestamp given by the Python time()
method includes microseconds as well.
As you can see, a timestamp, while being timezone independent, does not reveal much about the time and date.
In order to make sense of the timestamp we get, we can convert it to a datetime
object using another built-in method – fromtimestamp()
– in the datetime
module.
This method accepts two arguments – a timestamp and an optional timezone.
Once we convert the timestamp to a datetime
object, we can use the strftime()
method in the datetime
module to display the timestamp in a more readable format.
Let’s look at an example:
from datetime import datetime from time import time import pytz ts = time() current_time = datetime.fromtimestamp(ts).strftime('%a %b %d, %Y %I:%M:%S %p') current_time_in_ny = datetime.fromtimestamp(ts, pytz.timezone('America/New_York')).strftime('%a %b %d, %Y %I:%M:%S %p') current_time_in_ld = datetime.fromtimestamp(ts, pytz.timezone('Europe/London')).strftime('%a %b %d, %Y %I:%M:%S %p') print(ts) print(current_time) print(current_time_in_ny) print(current_time_in_ld)
Here, we first import the classes and modules that we need.
Next, we call the time()
method on line 5 to get the current timestamp and assign the result to a variable called ts
.
On line 7, we call the fromtimestamp()
method, passing ts
as an argument to the method. Here, we did not pass any timezone to the method. Hence, the method will convert the timestamp to the local time and date.
Next, we use the datetime
object returned by the fromtimestamp()
method to call the strftime()
method, passing '%a %b %d, %Y %I:%M:%S %p'
as the format string.
On lines 8 and 9, we call the fromtimestamp()
method again. However, this time, we pass a second argument to the method. On line 8, we pass the 'America/New_York'
timezone to the method and on line 9, we do the same with the 'Europe/London'
timezone.
Finally, on lines 11 to 14, we use the print()
function to print the current timestamp and the current time and date for the three timezones (local, New York and London).
If you run the code above, you’ll get an output similar to the following:
1601947617.6879241 Tue Oct 06, 2020 09:26:57 AM Mon Oct 05, 2020 09:26:57 PM Tue Oct 06, 2020 02:26:57 AM
The first line gives us the current timestamp.
The second gives us the date and time for my local timezone (which is GMT+8).
The third gives the current date and time for New York while the fourth gives the current date and time for London.
Practice Question
Now that you are familiar with different methods in Python to get the current time and date, let’s work on the practice question for today.
Today’s question requires us to write a function called message()
that does the following:
- Repeatedly prompt users to enter a message, or enter -1 to quit
- As long as the user does not enter -1, the program stores the message and the time that the message was created into a list.
- The time should be stored as a datetime string converted from a timestamp
- When users enter -1 to quit, the program displays the time and content of all the messages entered.
- The time should be displayed in the local timezone, using the following format – ‘Tue Oct 06 2020 09:30:01 AM’.
Expected Results
The output below shows an example of how to function works:
Enter your message or -1 to quit: Good morning Enter your message or -1 to quit: Time to start work Enter your message or -1 to quit: -1 Tue Oct 06 2020 09:47:44 AM: Good morning Tue Oct 06 2020 09:47:50 AM: Time to start work
Here, the user entered two messages – 'Good morning'
and 'Time to start work'
.
After the user enters -1 to quit the program, the program displays the time and content of the two messages entered.
Suggested Solution
Here’s the suggested solution for today’s practice.
from datetime import datetime from time import time def messageBoard(): messages = [] msgTime = 0 while True: msg = input('Enter your message or -1 to quit: ') msgTime = time() if msg != '-1': messages.append(datetime.fromtimestamp(msgTime).strftime('%a %b %d %Y %I:%M:%S %p') + ': ' + msg) else: break for i in messages: print(i) #Calling the function messageBoard()
Here, we first import the two modules that we need – datetime
and time
.
Next, we define a function called messageBoard()
that has no parameters.
Inside the function, we first declare and initialize two variables – messages
(which is a list for storing the time and content of the message entered) and msgTime
(which is an integer for storing the timestamp).
Next, we use a while True
loop (lines 7 to 13) to repeatedly prompt users to enter a message or -1 to quit.
After prompting users to enter their message, we use the time()
method to get the current timestamp and assign it to msgTime
.
Next, we use an if-else
statement (lines 10 to 13) to decide whether to append the time and content of the message entered to the messages
list. If the user did not enter -1, we append
datetime.fromtimestamp(msgTime).strftime('%a %b %d %Y %I:%M:%S %p') + ': ' + msg
to messages
.
Here, we first use the fromtimestamp()
method to convert msgTime
(the timestamp) to a datetime
object. Next, we use the resulting datetime
object to call the strftime()
method.
Finally, we concatenate the result of strftime()
with a colon (': '
) and the variable msg
.
A while True
loop runs indefinitely until we somehow exit the loop. In our suggested solution above, we exit the while True
loop in the else
block (lines 12 and 13) using a break
statement. This happens when the user enters -1.
Once we exit the while True
loop, we use a for
loop (lines 15 and 16) to print the content of messages
.
With that, the function is complete.
We call the function outside it on line 19.
About the pytz module
To install the pytz
module, we can use the pip package manager.
Installing PIP
If you’re using Python 2.7.9 (or greater) or Python 3.4 (or greater), PIP comes installed with Python by default. If you are using an older version of Python, you may need to install pip yourself.
You can refer to https://www.makeuseof.com/tag/install-pip-for-python/ for an excellent guide on installing PIP.
Adding Path to Environment Variables
After you install PIP, you will need to add its path (and Python’s path) to your environment variables.
For Windows 10 users,
Python should be located at
C:\Users\<username>\AppData\Local\Programs\Python\<Python Version>
PIP should be located at
C:\Users\<username>\AppData\Local\Programs\Python\<Python Version>\Scripts
You will need to replace <username> with your own username and <Python Version> with the name of the inner folder found in the Python folder. You’ll also need to add the two paths to “System Variables > Path”.
To do that, enter “env” in your search bar and click on the “Edit the system environment variables” option. Next, follow the steps shown in the diagram below:
For Mac and Linux users, unfortunately I do not have access to a Mac and Linux machine at the moment and can’t provide the specific information needed. A quick google search should give you the information you need.
Installing the pytz module
Once you have installed PIP, you can use that to install the pytz
module.
To do that, simply open a terminal (or command prompt) window, type
pip install pytz
and wait for the module to install.
After installing the module, you can open a Python shell and run the command
import pytz
If you do not get any errors, the module has been installed successfully.