You get the current time using datetime.datetime.now()
, format it in the following format: %H:%M:%S:%f
(H represents hours, M represents minutes, S represents seconds and f represents microseconds).
After that, we format the date by stripping the last 3 digits of the microseconds (f) with formatted_time = current_datetime.strftime("%H:%M:%S:%f")[:-3]
.
Next, we open the chosen log file using a context manager with with open("log.txt", "w") as log_file:
.
Inside the with
block, we write the date formatted to the log file with log_file.write(formatted_time)
.
The with
context manager will ensure that the file is automatically closed at the end of the block, making the use of log_file.close()
unnecessary.
note: you must open the file using the appropriate mode ('w' for write mode)
this is the code👇👇
import datetime
# Open the file using the context manager
with open("log.txt", "w") as log_file:
# Get the current datetime
current_datetime = datetime.datetime.now()
# Format the datetime as h:m:s:ms in the American format
formatted_time = current_datetime.strftime("%I:%M:%S.%f")[:-3]
# Write the formatted time to the log file
log_file.write(formatted_time)
# The file will be automatically closed when exiting the 'with' block
this is output 👇👇
13:40:15:063
H=13:M=40:S=15:F=063
Note:
- %H%M%S%f is 24 hour format
- %I%M%S%f is 12h formatù
strftime
(datetime to string), notstrptime
(string to datetime).