Hi All,

I am using the below code to write into a text file

# Write into log file
        inp=file(Doc\Log.txt, 'w')
        inp.write('Log file start')
        inp.close()

The text file 'Log.txt' is present in 'Doc' folder inside the application folder.
Now I want to create a text file with a time stamp every time the User runs the application and then write contents into it. How do I do this?

Any help is much appreciated!...

Regards,
Dinil

Here's an example of how to get the current date and time (as a string) using the datetime module.

import datetime
timestamp = str(datetime.datetime.now())
"""result ->
'2009-07-08 01:16:25.968000'
"""

Hope that helps!

Thanks... i used the below code and its working perfectly..
Thanks a lot :)

lt = time.localtime(time.time())
        lt=[lt[1], lt[2], lt[0], lt[3], lt[4],lt[5]]
        lt=str(lt[0])+"-"+str(lt[1])+"-"+str(lt[2])+"-"+str(lt[3])+"hr"+str(lt[4])+"min"+str(lt[5])+"s"

        strFile = "Log"+"_"+str(lt)+".txt"
        file = open(strFile , "a")
        file.write('Log file starts')
        file.close()

Thanks once again!

you can also try this it would constitute for a lot less coding

import time
#here you can format the date string anyway you want
time_stamp = time.strftime('%Y-%m-%d %H:%M:%S', (time.localtime(time.time())))
#output for time_stamp -> '2009-07-08 14:22:41'
#and format the text file name like such
strFile = "Log_%s.txt"%time_stamp

oh yes.. that makes it even more simpler.. Thanks a lot again....

if you're using windows then having file names with a colon(:) in it is not allowed and you'll get an exception

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.