How to Get Current Date and Time using Python
Getting the current date and time is common in Python for logging, timestamps, or scheduling. Using the datetime module, you can fetch local time, UTC, or time in specific time zones, and format it as needed.
Using datetime.now()
This method uses the datetime module to get the current local date and time as a datetime object.
import datetime
t = datetime.datetime.now()
print(t)
Output
2025-10-25 07:18:28.213080
Using datetime.now() with pytz
This method allows fetching the current date and time for a specific timezone, e.g., India or New York.
from datetime import datetime
import pytz
tz = pytz.timezone('Asia/Kolkata')
ct = datetime.now(tz)
print(ct)
Output
2025-10-25 12:48:49.608950+05:30
Explanation:
- pytz.timezone() creates a timezone object.
- datetime.now(tz_india) returns current date and time adjusted to the given timezone.
Using datetime.now() with zoneinfo
This method fetches the current date and time in UTC as a timezone-aware datetime object, useful for global applications.
from datetime import datetime
from zoneinfo import ZoneInfo
t = datetime.now(tz=ZoneInfo("UTC"))
print(t)
Output
2025-10-25 07:19:32.974627+00:00
Explanation:
- ZoneInfo("UTC") provides the Coordinated Universal Time (UTC) timezone.
- datetime.now(tz=...) returns the current date and time as a timezone-aware datetime object.
Using datetime.now().isoformat()
This method returns the current date and time in ISO format, useful for APIs and data exchange.
from datetime import datetime as dt
iso_time = dt.now().isoformat()
print(iso_time)
Output
2025-10-25T07:19:56.959542
Explanation:
- dt.now() gets current local date and time.
- isoformat() converts datetime object to ISO 8601 formatted string.