
PYTHON — Python- Current Time Overview
Any fool can write code that a computer can understand. Good programmers write code that humans can understand. — Martin Fowler
To get the current time in Python, you can use the datetime module. This tutorial will guide you through the process of getting, displaying, and formatting the current time. Additionally, you'll learn about working with different time formats and time zones.
First, let’s start by importing the datetime module and getting the current time:
from datetime import datetime
current_time = datetime.now()
print("Current Time:", current_time)In this example, datetime.now() returns the current local date and time. The print statement displays the current time.
You can also access specific attributes of the current time, such as the year, month, day, hour, minute, and second:
print("Year:", current_time.year)
print("Month:", current_time.month)
print("Day:", current_time.day)
print("Hour:", current_time.hour)
print("Minute:", current_time.minute)
print("Second:", current_time.second)The output will display the individual attributes of the current time.
Formatting the current time into a more readable form is another essential aspect. You can achieve this using the strftime method to specify the desired format:
formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted Time:", formatted_time)This code formats the current time as “Year-Month-Day Hour:Minute:Second” and prints the formatted time.
Dealing with time zones is also important, and Python provides support for time zone-aware datetime objects. You can use the pytz library to work with time zones:
import pytz
# Get the current time in UTC
utc_time = datetime.now(pytz.utc)
print("UTC Time:", utc_time)
# Convert to a specific time zone
eastern = pytz.timezone('US/Eastern')
eastern_time = utc_time.astimezone(eastern)
print("Eastern Time:", eastern_time)In this example, pytz.utc is used to get the current time in UTC, and then the time is converted to the Eastern time zone.
By following these examples, you can effectively work with the current time in Python and incorporate it into your applications for various time-related operations.






