Calculating Current Date and Time in Python
Import the “datetime” library so you can use it to calculate time:
from datetime import datetime
Defining time object of current time:
datetime_now = datetime.now()
datetime_now: is a variable that holds the current “datetime” object.
datetime: is the “datetime” object from the library we imported.
.now(): is a method of the “datetime” object that specifies the “datetime” at the moment it is called.
Next, define a variable that will host the current date and time formatted using a colon “:” and a slash “/” symbols.
datetime_text_format = datetime_now.strftime("%Y/%m/%d-%H:%M:%S.%f")
datetime_text_format: is a variable that will hold the formatted current date and time.
datetime_now: is the “datetime” object we created earlier.
.strftime(): a method of the “datetime” object that converts the “datetime” object into string using the format specified between the parentheses.
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 calculate current date and time and format it with custom setting:
# Importing "datetime" library for logging current time from datetime import datetime # Current time object datetime_now = datetime.now() # Text formatting datetime_text_format = datetime_now.strftime("%Y/%m/%d-%H:%M:%S.%f") # Printing output to console print(datetime_text_format)
Tested with python 3.9