python - 如何在 Python 中创建具有当前日期和时间的文件名?

标签 python

这是一个功能代码(创建文件成功)

sys.stdout = open('filename1.xml', 'w')

现在我正在尝试用当前日期/时间命名文件(我不是 Python 专家)

filename1 = datetime.now().strftime("%Y%m%d-%H%M%S")
sys.stdout = open(filename1 + '.xml', 'w')

我想写出一个带有确切日期和时间的文件名,它是一个xml文件,程序已经创建了,我只需要命名文件。上面的代码不起作用。

返回的错误:

  File "./fix.py", line 226, in <module>
    filenames = datetime.now().strftime("%Y%m%d-%H%M%S")
AttributeError: 'module' object has no attribute 'now'

最佳答案

虽然不使用 datetime,但这可以解决您的问题(回答您的问题),即获取具有您指定的当前时间和日期格式的字符串:

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

产量:

20120515-155045

所以你的文件名可以附加或使用这个字符串。

关于python - 如何在 Python 中创建具有当前日期和时间的文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10607688/

相关文章:

python - Plotly 静态图像导出出现 OSError : [WinError 193] %1 is not a valid Win32 application

python - 重新排列 CSV 数据

python - 在 python pandas 中指定多重索引的顺序

python - 在另一个用户定义函数中调用用户定义函数时出现名称错误

python - 将两个 numpy 数组中的值与 'if' 进行比较

Python 无法拆分零宽度 anchor ?

python - 从系列创建一个 pd.Dataframe

python - 与 Scikit-Learn 的 Logistic 回归相比,Tensorflow 的性能要差得多

python - pyinstaller 不使用 --onefile 捆绑 pyd 和 dll 文件

python - 如何从 ipywidget 选择小部件中获取值(value)?