首页 > 解决方案 > 在 Python 中将 .csv 文件命名为“From Time1 to Time2.csv”

问题描述

我想将一个 csv 文件命名为“从 Time1 到 Time2.csv”。

我正在使用以下代码:

import csv
from datetime import datetime
from datetime import datetime, timedelta
import time
 
# Note the current time
d1 = datetime.now()


# Note the time after 10 minutes from now
d2 = d1 + timedelta(minutes = 10)


# Create a csv file
with open(d1.strftime("%H_%M_%S.csv"), 'w') as file:
    writer = csv.writer(file)

上述代码生成一个文件“23_01_07.csv”,即 23 小时 1 分钟 7 秒(对应于 d1 字符串)

但是,我想将其命名为“23_01_07_to_23_11_07.csv”,即对应于 d1 和 d2 字符串。

如果有人可以请让我知道我们该怎么做,我将非常感激。

标签: pythonpython-3.xcsv

解决方案


请参阅 python 文档:https ://docs.python.org/3/library/datetime.html?highlight=strftime#datetime.datetime.strftime

d1.strftime("%H_%M_%S.csv")中,.strftime() 方法返回格式为“%H_%M_%S.csv”的字符串。所以,你想在 d1 和 d2 上使用这个方法,然后将字符串加上中间的“ to ”。

from_str = d1.strftime("%H_%M_%S")
to_str = d2.strftime("%H_%M_%S")
filename = from_str + "_to_" + to_str + ".csv"
with open(filename, 'w') as file:
    writer = csv.writer(file)

推荐阅读