how can I add a time stamp to a file

2
from datetime import datetime 

fecha=datetime.now()

how can I concatenate the date value to the name of a file

archivo=fecha+.log

so that I stay with this format

2018-10-29-12:31:31.log
    
asked by antoniop 29.10.2018 в 09:25
source

1 answer

2

The variable fecha is an object of type datetime . You have to get its representation as a string to be able to use it as a file name or to be able to concatenate things to it.

There are many ways to do this. For example, taking your model could be:

filename = str(fecha) + ".log"

But also using format strings, for example:

filename = "{}.log".format(fecha)

In this case you do not need to pass the date to str because the function format does so when you do not specify the type of what goes in between braces.

That will give you the default representation of the date, which looks like:

2018-10-29 11:58:26.251760

To have more precise control over the way you want it to become, you can use strftime() . In your case, if I'm not mistaken, you do not want to show fractions of a second, and you want the time to be linked to the date by a script. So this would be the format string to uar:

filename = "{}.log".format(fecha.strftime("%Y-%m-%d-%H:%M:%S"))
print(filename)
2018-10-29-11:58:26.log

Once you have created the file name in the variable filename , you can use it to create the file, for example:

with open(filename, "w") as f:
   f.write("Probando..\n")

That will create a file called 2018-10-29-11:58:26.log

    
answered by 29.10.2018 / 12:55
source