Get current time in python using the datetime library

Learning to work with time is an integral part of any programmer’s toolkit. Unlike JavaScript, which has the Date() class readily available with no import, the standard process in Python requires us to import a library.

The name of that library is datetime.

Let’s learn how to use datetime to retrieve the current time in Python. We’ll also go a few steps further and learn to create a datetime object with a specific time.


How Do I Import the datetime Library?

Although Python requires that we import the library, it does come standard so there’s no need to install anything. We use the import keyword and the library name like this:

import datetime

What this means is that we’ve imported the datetime library and will refer to it by the name of the library.


How Do I Use datetime?

Well, that’s a loaded question because datetime has a plethora of applications.

Let’s stay focused and get the current time. What’s tricky is that we’ve imported the datetime library, not the class itself. The class — which happens to have the same name — exists within the library.

To get the current timestamp, we’ll do the following:

dt = datetime.datetime.now()
print(dt) # 2020-02-01 11:24:31.436563

Notice how we’ve doubled up on datetime? The first is a reference to the library name, the second is the class itself, which is then followed by the method .now().

Don’t be fooled by the output, dt is not a simple string; it is a datetime object, similar to how JavaScript dates are Date() objects. You can do so many things with the datetime class, I recommend checking out the official documentation.

But wait, the title said current time, not timestamp. Once we’ve declared our datetime object with the current timestamp, we use the .time() method to return only the time portion.

time = dt.time() # 11:24:31.436563

As an added bonus, now that we’ve gone through the process step-by-step, we can clean up the code a bit if our only use is to get the current time.

from datetime import datetime as dttime = dt.now().time()print(time)) # 11:24:31.436563

We did three new things here:

  • Imported the datetime class directly from the library.
  • Assigned a custom identifier for the datetime class.
  • Chained the .now() and .time() methods together.

Getting a Specific Timestamp

To create a datetime object for a specific point in time, we need to pass arguments to the initialization of our object.

We’ll pass — in this order — the yearmonthdatehoursminutesseconds, and microseconds. It’s easy to remember because the units get progressively smaller.

from datetime import datetime as dttime = dt(2020,2,1,11,24,31,436563)print(time) # 2020-02-01 11:24:31.436563

Conclusion

If this is your first time (pun intended) using Python’s datetime library then I hope it was helpful and let me know how it goes. If you’re a grizzled vet, then share your favorite datetime methods in the comments below. Thanks everyone!