
PYTHON — Tell the Time in Python
Measuring programming progress by lines of code is like measuring aircraft building progress by weight. — Bill Gates
Telling the Time in Python
When working with Python, you may often need to tell the time. In this tutorial, we’ll cover how you can achieve this using the datetime module. Let’s get started by creating a datetime object and displaying the current time in Python.
Importing the datetime Module To begin, you’ll need to import the datetime module in Python. You can do this by using the following code:
from datetime import datetime as dtCreating a Datetime Object Next, you can instantiate a datetime object by setting a variable name of your choice equal to the dt.now() method. For example:
now = dt.now()Displaying the Current Time When you call your datetime object, you can see that Python returns several numbers. However, in this format, the meaning of each number is not very clear. To get a more readable output, you can use the print() function when calling your object.
print(now)Formatting the Time When printing datetimes, Python closely follows formatting standards known as ISO 8601 formatting. To specifically call the ISO-formatted date and time in Python, you can use the .isoformat() method.
print(now.isoformat())You can also remove the T separator by adding a separator argument to the .isoformat() method using a single space as the separator instead, like so:
print(now.isoformat(sep=' '))In this tutorial, you learned to create datetime objects and how to call datetime objects using the print() and .isoformat() functions.
In the next lesson, you will learn about some of the different methods and attributes that can be called on datetime objects.






