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.
Source Code: Click here to download the free source code for getting and using the current time in Python.
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:
>>> 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.
Note: The datetime
object that you get here isn’t time zone aware. Usually your operating system can resolve the time zone correctly, but the datetime
object itself currently has no time zone information. You’ll get into time zone–aware objects in a later section of this tutorial.
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:
>>> 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:
>>> 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.
Note: For the .weekday()
method, Monday is 0
and Sunday is 6
. For .isoweekday()
, Monday is 1
and Sunday is 7
.
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:
>>> 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.
Note: Python’s f-strings supports the same format codes as .strftime()
. You can use them like this:
>>> f"{datetime.now():%A, %B %d}"
'Tuesday, November 22'
In f-strings, you use colon (:
) to separate your expression and the corresponding format code.
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:
>>> 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.
Note: Since the datetime
object that you’ve created isn’t time zone aware, the timestamp you generated may not actually be Unix time! It’s probably fine, as long as your system has its time settings configured properly.
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:
>>> 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.
Note: The name of the time zone will also depend on your operating system. The datetime
module often communicates with the operating system to get the time and time zone information, among other things, like your preferred language.
The zoneinfo
module was added in Python 3.9 to give you access to the IANA time zone database.
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:
>>> 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:
>>> 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.
Source Code: Click here to download the free source code for getting and using the current time in Python.
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