Basics Intermediate Advanced
aialgorithmsapibest-practicescareercommunitydatabasesdata-sciencedata-structuresdata-vizdevopsdjangodockereditorsflaskfront-endgamedevguimachine-learningnewsnumpyprojectspythonstdlibtestingtoolsweb-devweb-scraping

How to Get and Use the Current Time in Python
Table of Contents
Recommended Course
Getting thecurrent time in Python is a nice starting point for many time-related operations. One very important use case is creatingtimestamps. In this tutorial, you’ll learn how toget,display, andformat the current time with thedatetime 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 toread attributes of the current time, like the year, minutes, or seconds. To make the time more easily readable, you’ll explore options forprinting it. You’ll also get to know differentformats of time and learn how computersrepresent time, how toserialize time, and how to deal withtime 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 thedatetimeclass in thedatetime module:
>>>fromdatetimeimportdatetime>>>now=datetime.now()>>>nowdatetime(2022, 11, 22, 14, 31, 59, 331225)>>>print(now)2022-11-22 14:31:59.331225The class method.now() is aconstructor method that returns adatetime object. When the REPL evaluates thenow variable, you get arepresentation of thedatetime object. It can be pretty hard to tell what each number means. But if you explicitly print thenow variable, then you get a slightly different output that presents the information in a familiar timestamp format.
Note: Thedatetime object that you get here isn’t time zone aware. Usually your operating system can resolve the time zone correctly, but thedatetime object itself currently has no time zone information. You’ll get into time zone–aware objects in alater section of this tutorial.
You may recognize the format of the printeddatetime object. It closely follows aninternational 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 aT character, but the defaultdatetime object passed through theprint() 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. Thedatetime class internally uses its.isoformat() method when printing. Since.isoformat() is just aninstance method, you can call it directly from anydatetime 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 separatorT is used. The way that thedatetime class has implemented itsspecial instance method.__str__() under the hood, though, is with a single space as thesep 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:
>>>fromdatetimeimportdatetime>>>now=datetime.now()>>>print(f"""...{now.month= }...{now.day= }...{now.hour= }...{now.minute= }...{now.weekday()= }...{now.isoweekday()= }"""...)now.month = 11now.day = 22now.hour = 14now.minute = 31now.weekday() = 1now.isoweekday() = 2In this snippet, you use a triple-quotedf-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 thedir() function with adatetime object to list the names available in the currentscope. Or you can check out thedocumentation fordatetime. 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 is0 and Sunday is6. For.isoweekday(), Monday is1 and Sunday is7.
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 aformat code as an argument. A format code is a string with a bunch of specialtokens that’ll be replaced with information from thedatetime object.
The.strftime() method will give you loads of options for how exactly to represent yourdatetime object. For instance, take this format:
>>>fromdatetimeimportdatetime>>>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 anold C standard. These codes are similar to the oldprintf string formatting style, but they’re not the same.
Thedocumentation 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 namedstrftime.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 theUnixoperating system was being developed.
The decision was to represent all times as the number of seconds that have passed since midnightUTC on January 1, 1970. This point in time is also known as the Unixepoch. The time system is known asUnix 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 anotherdatetime method:
>>>fromdatetimeimportdatetime>>>datetime.now().timestamp()1669123919.331225The.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 thedatetime 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 theGregorian 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–awaredatetime objects.
Get Time Zone–Aware Python Time and Date Objects
The unambiguity of Unix timestamps is attractive, but it’s generally better toserialize times and dates with the ISO 8601 format because, in addition to being easy for computers toparse, it’s alsohuman 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 theZen of Python,readability counts.
If you want to represent yourdatetime objects in completely unambiguous terms, then you’ll first need to make your objecttime zone aware. Once you have a time zone–aware object, the time zone information gets added to your ISO timestamp:
>>>fromdatetimeimportdatetime>>>now=datetime.now()>>>print(now.tzinfo)None>>>now_aware=now.astimezone()>>>print(now_aware.tzinfo)Romance Standard Time>>>now_aware.tzinfodatetime.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 thenow object doesn’t have any time zone information because its.tzinfo attribute returnsNone. When you call.astimezone() onnow without any arguments, the local system time zone is used to populate.tzinfo with atimezone object.
Atimezone object is essentially just an offset from UTC time and a name. In the example, the name of the local time zone isRomance 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. Thedatetime module often communicates with the operating system to get the time and time zone information, among other things, like your preferred language.
Thezoneinfo module was added inPython 3.9 to give you access to theIANA time zone database.
Now that thedatetime object has atimezone 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 nicelynormalized:
>>>fromdatetimeimportdatetime,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 thetimezone.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 acceptsZ in place of+00:00 to represent UTC time. This is sometimes referred to asZulu 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 adatetime object and have seen how to pick out different attributes of the object. You’ve also examined a few ways to output thedatetime 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 yourdatetime object time zone aware.
If you’re looking to time how long things take, then check out the tutorialPython Timer Functions: Three Ways to Monitor Your Code. To dive deeper into thedatetime module, check outUsing Python datetime to Work With Dates and Times.
Now you can say thattime really is on your side! How do you use thedatetime 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.
Recommended Course
🐍 Python Tricks 💌
Get a short & sweetPython Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

MasterReal-World Python Skills With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
MasterReal-World Python Skills
With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
What Do You Think?
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 andget answers to common questions in our support portal.
Looking for a real-time conversation? Visit theReal Python Community Chat or join the next“Office Hours” Live Q&A Session. Happy Pythoning!
Keep Learning
Keep reading Real Python by creating a free account or signing in:
Already have an account?Sign-In





