Telling the Time in Python

00:00 It’s time for you to create your first datetime object. To begin, you’ll need to import the datetime module in Python. You can do this by typing in the following code: from datetime import datetime as dt. I prefer to import the module as dt.

00:15 However, this is not required. Next, you can instantiate a datetime object by setting a variable name of your choice equal to dt.now() method. For this example, I’ve named my datetime object now, but you can name it something different if you wish.

00:32 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.

00:40 In order to get a more readable output, you can use the print() function when calling your object.

00:47 As you can see, the output is now more readable, showing the year, month, and then the date followed by the current time of day.

00:54 When printing datetimes, Python closely follows formatting standards known as ISO 8601 formatting. You may have seen this before, as it is a common method of formatting times and dates.

01:06 You can also specifically call the ISO-formatted date and time in Python by using the .isoformat() method.

01:14 As you can see, this output very closely aligns with using the print() function alone. However, in this example, you can see a T, which acts as the standard separator between the date and the time.

01:25 If you’d like to remove the T separator, you can add a separator argument to the .isoformat() method using a single space as the separator instead, like so.

01:41 In this lesson, you learned to create datetime objects. You also learned how to call datetime objects using the print() and .isoformat() functions.

01:50 In the next lesson, you will learn about some of the different methods and attributes that can be called on datetime objects.

Become a Member to join the conversation.