How to Get and Use the Current Time in Python

How to Get and Use the Current Time in Python

by Ian Currie intermediate

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: How to Get the Current Time in Python

Getting the current time in Python is a nice starting point for many time-related operations. One very important use case is creating timestamps. In this tutorial, you’ll learn how to get, display, and format the current time with the datetime module.

To effectively use the current time in your Python applications, you’ll add a few tools to your belt. For instance, you’ll learn how to read attributes of the current time, like the year, minutes, or seconds. To make the time more easily readable, you’ll explore options for printing it. You’ll also get to know different formats of time and learn how computers represent time, how to serialize time, and how to deal with time zones.

How to Tell the Time in Python

The most straightforward way to get and print the current time is to use the .now() class method from the datetime class in the datetime module:

Python
>>> from datetime import datetime
>>> now = datetime.now()

>>> now
datetime(2022, 11, 22, 14, 31, 59, 331225)

>>> print(now)
2022-11-22 14:31:59.331225

The class method .now() is a constructor method that returns a datetime object. When the REPL evaluates the now variable, you get a representation of the datetime object. It can be pretty hard to tell what each number means. But if you explicitly print the now variable, then you get a slightly different output that presents the information in a familiar timestamp format.

You may recognize the format of the printed datetime object. It closely follows an international standard, ISO 8601, for formatting time and dates. You’ll find this format in many places!

There’s a slight deviation from the ISO 8601 standard in the format that Python uses, though. The standard says that the date and the hour parts of the timestamp should be separated by a T character, but the default datetime object passed through the print() function separates them with a single space.

Python, being ever extensible and customizable, enables you to customize the format in which it prints the timestamp. The datetime class internally uses its .isoformat() method when printing. Since .isoformat() is just an instance method, you can call it directly from any datetime object to customize the ISO timestamp:

Python
>>> datetime.now().isoformat()
'2022-11-22T14:31:59.331225'

>>> datetime.now().isoformat(sep=" ")
'2022-11-22 14:31:59.331225'

You’ll note that when you call .isoformat() without any arguments, the standard ISO 8601 separator T is used. The way that the datetime class has implemented its special instance method .__str__() under the hood, though, is with a single space as the sep argument.

Being able to get the full date and time is great, but sometimes you might be looking for something specific. Maybe you only want the month or day, for example. In those cases, you can choose from a bunch of attributes:

Python
>>> from datetime import datetime
>>> now = datetime.now()
>>> print(f"""
... {now.month = }
... {now.day = }
... {now.hour = }
... {now.minute = }
... {now.weekday() = }
... {now.isoweekday() = }"""
... )
now.month = 11
now.day = 22
now.hour = 14
now.minute = 31
now.weekday() = 1
now.isoweekday() = 2

In this snippet, you use a triple-quoted f-string with the = sign within the curly brackets to output the expressions and their results.

Go ahead and explore the different attributes and methods by calling the dir() function with a datetime object to list the names available in the current scope. Or you can check out the documentation for datetime. Either way, you’ll find a wealth of options.

You’ll note that the results from the last example are generally numbers. This may suit you fine, but maybe showing weekdays as numbers isn’t ideal. It can also be especially confusing since the .weekday() and .isoweekday() methods return different numbers.

An ISO timestamp is nice, but maybe you want something even more readable than an ISO timestamp. For example, milliseconds might be a bit much for a person to read. In the next section, you’ll learn how to format your timestamps in any way you like.

Format Timestamps for Readability

To make it easy to output times in a custom, human-readable way, datetime has a method called .strftime(). The .strftime() method takes a format code as an argument. A format code is a string with a bunch of special tokens that’ll be replaced with information from the datetime object.

The .strftime() method will give you loads of options for how exactly to represent your datetime object. For instance, take this format:

Python
>>> from datetime import datetime

>>> datetime.now().strftime("%A, %B %d")
'Tuesday, November 22'

In this example, you used the following format codes:

  • %A : Weekday full name
  • %B : Month full name
  • %d : Numeric day of the month

The comma in the format string and the literal spaces are printed as is. The .strftime() method only replaces what it recognizes as codes. Format codes in .strftime() always begin with a percentage sign (%), which follows an old C standard. These codes are similar to the old printf string formatting style, but they’re not the same.

The documentation for format codes has a nice table showing you all the different format codes that you can use. There’s also a nice cheatsheet at the aptly named strftime.org website. Go check them out.

So now you can get the time and format it to your liking. That should get you going for your basic time-telling needs, but maybe you’re curious about how computers represent and deal with time internally and how you might store times in files or databases. In the next section, you’ll be getting into just that.

Get the Current Unix Time in Python

Computers like numbers. But dates and times are funny human numbers that follow funny rules. Twenty-four hours in a day? Sixty minutes in an hour? Whose bright ideas were these?

To simplify matters, and seeing as computers don’t mind large numbers, a decision was made sometime while the Unix operating system was being developed.

The decision was to represent all times as the number of seconds that have passed since midnight UTC on January 1, 1970. This point in time is also known as the Unix epoch. The time system is known as Unix time. Most computer systems today—even Windows—use Unix time to represent times internally.

Unix time at midnight UTC on the January 1, 1970, is zero. If you want to know the current Unix time, then you can use another datetime method:

Python
>>> from datetime import datetime

>>> datetime.now().timestamp()
1669123919.331225

The .timestamp() method returns the number of seconds since the Unix epoch to a high level of precision. After all, underneath all the attributes and methods, every date is little more than a large number for most computers.

For the most part, you can leave Unix time alone. It’s a way to represent time that works well for computers, but not for people who are used to a human calendar like the Gregorian calendar. Unix timestamps will crop up in your date and time adventures, though, so they’re definitely good to know about.

One of the nicest things about a properly generated Unix timestamp is that it unambiguously captures a moment worldwide. The Unix epoch is always in UTC, so there’s no ambiguity in terms of time zone offsets—that is, if you can reliably create timestamps that have no offset from UTC.

But unfortunately, you’ll often have to deal with the messiness of time zones. Never fear, though! In the next section, you’ll get to know time zone–aware datetime objects.

Get Time Zone–Aware Python Time and Date Objects

The unambiguity of Unix timestamps is attractive, but it’s generally better to serialize times and dates with the ISO 8601 format because, in addition to being easy for computers to parse, it’s also human readable, and it’s an international standard.

Whats more, even though Unix timestamps are somewhat recognizable, they could be mistaken for representing something else. They’re just numbers, after all. With an ISO timestamp, you immediately know what it represents. To quote the Zen of Python, readability counts.

If you want to represent your datetime objects in completely unambiguous terms, then you’ll first need to make your object time zone aware. Once you have a time zone–aware object, the time zone information gets added to your ISO timestamp:

Python
>>> from datetime import datetime
>>> now = datetime.now()

>>> print(now.tzinfo)
None

>>> now_aware = now.astimezone()

>>> print(now_aware.tzinfo)
Romance Standard Time

>>> now_aware.tzinfo
datetime.timezone(datetime.timedelta(seconds=3600), 'Romance Standard Time')

>>> now_aware.isoformat()
'2022-11-22T14:31:59.331225+01:00'

In this example, you start off by demonstrating that the now object doesn’t have any time zone information because its .tzinfo attribute returns None. When you call .astimezone() on now without any arguments, the local system time zone is used to populate .tzinfo with a timezone object.

A timezone object is essentially just an offset from UTC time and a name. In the example, the name of the local time zone is Romance Standard Time, and the offset is 3,600 seconds, or one hour.

Now that the datetime object has a timezone object, you can consider it time zone aware. So when you call .isoformat() on the time zone–aware object, you’ll notice that +01:00 is added to the end. This represents the one-hour offset from UTC time.

If you were in a different location, such as Lima, Peru, then your .isoformat() output might look like this:

Python
>>> now_aware.isoformat()
'2022-11-22T07:31:59.331225-06:00'

The time will be different, and you’ll see the UTC offset is now -06:00. So now your timestamps look good and are unambiguous in terms of what time they represent.

You could even go a step further, as many do, and store your timestamps in UTC time, so that everything is nicely normalized:

Python
>>> from datetime import datetime, timezone
>>> now = datetime.now()

>>> now.isoformat()
'2022-11-22T14:31:59.331225'

>>> now_utc = datetime.now(timezone.utc)
>>> now_utc.isoformat()
'2022-11-22T13:31:59.331225+00:00'

Passing the timezone.utc time zone to the .now() constructor method will return a UTC time. Note that the time is offset from the local time in this example.

The ISO 8601 standard also accepts Z in place of +00:00 to represent UTC time. This is sometimes referred to as Zulu time, which is what it’s often called in aviation.

In aviation, you always operate in UTC time. Operating in a common time, regardless of location, is critical in a field like aviation. Imagine air traffic control having to deal with every plane reporting estimated landing times according to their place of origin. That kind of situation would be a recipe for confusion, and disaster!

Conclusion

In this tutorial, you’ve told the time! You’ve generated a datetime object and have seen how to pick out different attributes of the object. You’ve also examined a few ways to output the datetime object in different formats.

You’ve also acquainted yourself with Unix time and ISO timestamps and explored how you can represent your timestamp unambiguously. For this, you’ve dipped your toes into the complex world of time zones and made your datetime object time zone aware.

If you’re looking to time how long things take, then check out the tutorial Python Timer Functions: Three Ways to Monitor Your Code. To dive deeper into the datetime module, check out Using Python datetime to Work With Dates and Times.

Now you can say that time really is on your side! How do you use the datetime module? Share your ideas and war stories in the comments below.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: How to Get the Current Time in Python

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Ian Currie

Ian Currie Ian Currie

Ian is a Python nerd who relies on it for work and much enjoyment.

» More about Ian

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Master Real-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

Master Real-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal.


Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Keep Learning

Related Tutorial Categories: intermediate

Recommended Video Course: How to Get the Current Time in Python