Retrieving Current Time in Python
Need to access the current time in your Python scripts? Here's how to accomplish this:
Using the datetime Module
The recommended and most comprehensive approach involves importing the datetime module:
>>> import datetime
Retrieving Date and Time
To obtain both the date and time, use the datetime.datetime.now() method:
>>> now = datetime.datetime.now() >>> print(now) >>> # Output: >>> 2023-03-08 10:15:30.123456
Retrieving Time Only
If only the time is needed, use the now.time() method:
>>> now.time() >>> # Output: >>> 10:15:30.123456
Customizing Display
You can customize the output format by accessing individual fields within the datetime object, such as year, month, day, hour, minute, and second.
>>> print("Year:", now.year) >>> print("Month:", now.month) >>> print("Day:", now.day) >>> print("Hour:", now.hour) >>> print("Minute:", now.minute) >>> print("Second:", now.second)
Simplifying Imports
For convenience, you can import the datetime object directly from the datetime module:
>>> from datetime import datetime
This eliminates the need to prefix datetime. before each datetime method call.
The above is the detailed content of How Can I Get and Format the Current Time in Python?. For more information, please follow other related articles on the PHP Chinese website!