简体   繁体   中英

How can I insert the Python timestamp time.strftime into a pathname for the filename output?

Goal is to put a date-timestamp as the filename for output of photos of a Python script.

timestr=time.strftime("%Y%m%d-%H%M%S")

gives me exactly what I want for print (timestr) but I cannot figure out how to insert this string for the file name into what I am given by:

camera.capture('/path/to/save/file.jpg')

you are halfway done, now just try to change the file name that you are saving

dir_path='path/to/save/'
timestr=time.strftime("%Y%m%d-%H%M%S")
file_name=timestr + '.jpg'     #file name
path=dir_path+file_name        #abs path of file
camera.capture(path)          

Here's a proper solution:

import time
import os

timestr, file_path = time.strftime("%Y%m%d-%H%M%S"), '/path/to/save/file.jpg'
filename, file_extension = os.path.splitext(file_path)
output = "{0}_{1}{2}".format(filename, timestr, file_extension)
print timestr, filename, output

output variable will have the desired result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM