python - 在 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 字符串。
如果有人可以请让我知道我们该怎么做,我将非常感激。
解决方案
请参阅 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)
推荐阅读
- python-3.x - 随机功能在不和谐机器人中不起作用
- svg - 当另一端结束时,svg 动画不起作用
- python - 如何在不使用外部模块的情况下在 Python 中打开/创建图像
- javascript - 字符串树枝文件中的 Javascript 变量
- handlebars.js - 在模板主题中动态获取车把路径
- r - 如何返回 R 中向量或数据框中每个元素的索引?
- javascript - 使用隐藏输入将 Javascript 变量传递给 PHP
- wordpress - 基于先前分类值 wordpress 的限制值分类
- javascript - JavaScript 和 HTML 按钮 onclick() 不工作
- python - Unescape Hex 代码点 \u0026 而不改变 Python 中的编码