— Python, Datetime, Time — 1 min read
Python provides several ways to get the current time, primarily through the datetime and time modules. This article will guide you through various methods to retrieve and format the current date and time in Python.
The datetime module is commonly used for handling date and time in Python.
1import datetime2now = datetime.datetime.now()3print(now) # Output: YYYY-MM-DD HH:MM:SS.ffffffThis gives you the current date and time down to microseconds.
If you only need the current time:
1from datetime import datetime2current_time = datetime.now().time()3print(current_time) # Output: HH:MM:SS.ffffffAlternatively, you can use the time module, which is part of Python's standard library.
The time module allows for more control over formatting.
1from time import gmtime, strftime2formatted_time = strftime("%Y-%m-%d %H:%M:%S", gmtime())3print(formatted_time) # Output: YYYY-MM-DD HH:MM:SSThis example uses gmtime() for UTC time. You can replace it with localtime() for local time.
Both datetime and time modules provide ways to format the date and time output:
%Y-%m-%d %H:%M:%S - Standard date and time format.%A, %B %d, %Y - Weekday, month, day, year.Retrieving and formatting the current date and time in Python can be easily achieved with the datetime and time modules. Understanding these modules allows you to handle date and time effectively in your Python applications.