How to Get Current Date and Time in Python Easily
Use the
datetime module in Python to get the current date and time. Call datetime.datetime.now() to get the current date and time as a datetime object.Syntax
To get the current date and time, import the datetime module and use the datetime.now() method. This returns a datetime object with the current local date and time.
import datetime: Loads the datetime module.datetime.datetime.now(): Gets current date and time.
python
import datetime
current_datetime = datetime.datetime.now()Example
This example shows how to print the current date and time in a readable format.
python
import datetime current_datetime = datetime.datetime.now() print("Current date and time:", current_datetime)
Output
Current date and time: 2024-06-15 14:30:45.123456
Common Pitfalls
One common mistake is to forget importing the datetime module before using it. Another is confusing datetime.now() with datetime.today(), which behaves similarly but is less explicit. Also, using time.time() returns a timestamp, not a datetime object.
python
import datetime # Wrong: forgetting to import datetime # current_datetime = datetime.now() # This will cause an error # Right: current_datetime = datetime.datetime.now() print(current_datetime)
Quick Reference
| Function | Description |
|---|---|
| datetime.datetime.now() | Returns current local date and time as datetime object |
| datetime.date.today() | Returns current local date only |
| datetime.datetime.utcnow() | Returns current UTC date and time |
| time.time() | Returns current time as timestamp (seconds since epoch) |
Key Takeaways
Use datetime.datetime.now() to get current local date and time.
Always import the datetime module before using it.
datetime.datetime.now() returns a datetime object you can format or manipulate.
For just the date, use datetime.date.today().
Avoid confusing timestamps from time.time() with datetime objects.