0

i am trying to print out the current hours mins seconds and milliseconds to a file accurately but cant seem to find the right formatting for the date format

log_file.write(datetime.datetime.strptime(f"{datetime.datetime.now()}","%H-%M-%S-%f"))

I'm using this and want it to output as time from when python file was opened like:

0:0:5:123 h:m:s:ms

1
  • You need to use strftime (datetime to string), not strptime (string to datetime).
    – Stitt
    Commented Jul 26, 2023 at 11:33

3 Answers 3

1

If you're trying to convert datetime to a string, you can use strftime function with the datetime object.

Code:

import datetime

print(datetime.datetime.now().strftime("%H-%M-%S-%f"))

Output:

19-04-37-298200
0

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ù
2
  • FYI if you use open's context manager you can avoid to explicitly log_file.close(): it's generally a good practice example Commented Jul 26, 2023 at 12:00
  • Hi you are absolutely right! Using the open context manager with the with statement is a really good practice and can help you avoid the need to explicitly close the file. Thanks for the feedback I will modify the code using the with Commented Jul 26, 2023 at 12:08
0

The strftime() function should work. See the code below for an example.

import datetime

now = datetime.datetime.now()
formatted_now = now.strftime("%H:%M:%S:%f")

print(formatted_now)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.