how can I add a time stamp to a file

from datetime import datetime

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


so that I stay with this format

asked by antoniop 29.10.2018 в 09:25

1 answer


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"))

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:

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

answered by 29.10.2018 / 12:55