Generating Current Date and Time in Python
You can generate Python’s current date and time using the “datetime” library.
For more details check python datetime library page and python datetime.datetime object.
To start, we’ll be leveraging a module named “datetime.” It is a part of Python’s standard library, which means you don’t need to install anything to use it. Importing this module will provide the required functions to obtain Python’s current date time.
from datetime import datetime
After importing the datetime module, we will call upon the function “now().” This function is a direct method to capture the current date and time, as shown in the following code:
datetime_now = datetime.now()
The “datetime_now” variable here holds the value returned by “datetime.now()”, which represents the current date and time. When you print this variable, you will see an output that includes the present moment’s year, month, day, hours, minutes, and seconds.
To make this Python current date time more readable or formatted according to your needs, Python provides a method called strftime. This method allows you to format date and time objects into readable strings.
datetime_string_format = datetime_now.strftime("%Y/%m/%d-%H:%M:%S.%f")
In the code above, “strftime” is used with the format string “%Y-%m-%d %H:%M:%S.%f”, which directs Python to format the date and time as “YYYY-MM-DD HH:MM:SS:Milliseconds”. This method is how you format the Python current date time. You can customize the format string to suit your needs. For example, if you prefer the date to be in the format “DD/MM/YYYY”, you would change the format string to “%d/%m/%Y”.
Date and Time formatting descriptions:
%Y: Four-digit year. Example: current year – 2021.
%m: Two-digit month. Example: September – 09.
%d: Two-digit day. Example: 4th of September – 04.
%H: Two-digit time in 24-hour format. Example: 2 in the morning or 2 AM – 02.
%M: Two-digit minutes. Example: 7 minutes – 07.
%S: Two-digit seconds. Example: 3 seconds – 03.
%f: 6 digit microseconds.
Date Time Example by this formatting: 2021/09/04-02:07:03.111406
For all the format codes, visit python strftime() method behavior and format codes.
The Full Script
The full script combining all the lines from above to generate the python current date time and format it with custom settings:
# Importing "datetime" library for logging current time from datetime import datetime # Current time object datetime_now = datetime.now() # Text formatting datetime_string_format: str = datetime_now.strftime("%Y/%m/%d-%H:%M:%S.%f") # Printing output to console print(datetime_string_format)