Get Current Time in Python Effortlessly
How to Get and Use the Current Time in Python
Getting the current time in Python is a crucial step in many time-related operations. One common use case is creating timestamps. In this tutorial, you will learn how to get, display, and format the current time in Python using the datetime
module.
To effectively utilize the current time in your Python applications, you need to familiarize yourself with different tools. You will learn how to read attributes of the current time, such as the year, minutes, or seconds. Additionally, you will explore options for printing and formatting the time. Furthermore, you will delve into different time formats and how computers represent time, as well as dealing with time zones.
How to Tell the Time in Python
The simplest way to obtain and print the current time is by using the .now()
class method from the datetime
module.
Python
The class method .now()
returns a datetime
object, which represents the current date and time. By explicitly printing the now
variable, you can obtain a timestamp in the familiar YYYY-MM-DD HH:MM:SS.mmm
format.
Here’s an example output:
However, note that the datetime
object obtained this way is not time zone aware. While your operating system can resolve the time zone correctly, the datetime
object itself does not have time zone information.
It is worth mentioning that the printed datetime
object follows the ISO 8601 standard for time and date formatting, which is an international standard. However, Python deviates slightly from the standard by using a space instead of the T
character to separate the date and time parts of the timestamp.
Python allows you to customize the format in which the timestamp is printed. The datetime
class internally uses the .isoformat()
method to print the timestamp. You can call this method directly from any datetime
object to customize the ISO timestamp format:
Python
The above code will produce a timestamp in the format 'YYYY-MM-DDTHH:MM:SS.mmmmmm'
.
By utilizing these methods, you can easily obtain and print the current time in Python.