输入文件名的时间戳

时间:2017-11-01 16:29:00

标签: python python-2.7 python-3.x timestamp

我想将时间戳插入到python脚本的输出文件名中,例如:20011231_230159_md5_filelist.csv

我无法插入代码。

这是输出文件名需要时间戳的脚本的 end

try:

    my_last_data = get_md5(file_full_path) + ", " + get_last_write_time(file_full_path) + ", " + get_size(
        file_full_path) + ", " + file_full_path + "\n"

    with open("md5_filelist.csv", "a") as my_save_file:
        my_save_file.write(my_last_data)

    print(str(file_full_path) + "  ||| Done")

except:
    print("Error On " + str(file_full_path))

这是我正在与之斗争的时间戳代码(虽然不确定它是否是最适合此目的的行):

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

我尝试以各种方式插入,不起作用。任何提示?

2 个答案:

答案 0 :(得分:1)

感谢@ pm-2ring(见评论),解决方案:

timestr = time.strftime("%Y%m%d_%H%M%S")
(timestr + "_md5_filelist.csv", "a")
脚本中的

try:

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

    my_last_data = get_md5(file_full_path) + ", " + get_last_write_time(file_full_path) + ", " + get_size(
        file_full_path) + ", " + file_full_path + "\n"

    with open(timestr + "_md5_filelist.csv", "a") as my_save_file:
        my_save_file.write(my_last_data)

    print(str(file_full_path) + "  ||| Done")

except:
    print("Error On " + str(file_full_path))

答案 1 :(得分:0)

这就是你所需要的一切。

try:
    my_last_data = get_md5(file_full_path) + ", " + get_last_write_time(file_full_path) + ", " + get_size(
        file_full_path) + ", " + file_full_path + "\n"

    with open("{}md5_filelist.csv".format(timestr), "a") as my_save_file:
        my_save_file.write(my_last_data)

    print(str(file_full_path) + "  ||| Done")
except:
    print("Error On " + str(file_full_path))

您没有在代码中的任何位置使用timestr。