在 python 中创建一个包含当前日期和时间的文件名
create a file name with the current date & time in python
我使用 datedime
在 Python 中创建了一个目录名称,如下所示:
代码:
import os
from datetime import datetime
os.mkdir(f"{datetime.now()}")
os.listdir()
当我在终端中使用 ls
命令时,我得到了以下结果:
当我得到 dir
个名字 Python:
代码:
os.listdir()
输出:
['.gitlab-ci.yml',
'public',
'AUTHORS',
'.dockerignore',
'requirements',
'.git',
'Dockerfile',
'manage.py',
'.editorconfig',
'2020-01-11 12:53:08.425169',
'logs',
'.idea',
'branch.sh',
'initial_media',
'README.md',
'__pycache__',
'setup.cfg',
'.gitignore',
'venv']
解法:
我用strftime()
方法解决了:
代码:
import os
from datetime import datetime
os.mkdir(f'{datetime.now().strftime("%Y-%m-%d_%I-%M-%S_%p")}')
TL;DR
为什么 dir
名称中出现单引号?是 datetime __str__
或 __repr__
函数的问题吗?
您的目录名可能没有引号。它只是这样显示的。尝试将 space 添加到您的 strftime
示例中,看看会发生什么:
os.mkdir(f'{datetime.now().strftime("%Y-%m-%d_%I %M-%S_%p")}')
见Why is 'ls' suddenly wrapping items with spaces in single quotes?
我使用 datedime
在 Python 中创建了一个目录名称,如下所示:
代码:
import os
from datetime import datetime
os.mkdir(f"{datetime.now()}")
os.listdir()
当我在终端中使用 ls
命令时,我得到了以下结果:
当我得到 dir
个名字 Python:
代码:
os.listdir()
输出:
['.gitlab-ci.yml',
'public',
'AUTHORS',
'.dockerignore',
'requirements',
'.git',
'Dockerfile',
'manage.py',
'.editorconfig',
'2020-01-11 12:53:08.425169',
'logs',
'.idea',
'branch.sh',
'initial_media',
'README.md',
'__pycache__',
'setup.cfg',
'.gitignore',
'venv']
解法:
我用strftime()
方法解决了:
代码:
import os
from datetime import datetime
os.mkdir(f'{datetime.now().strftime("%Y-%m-%d_%I-%M-%S_%p")}')
TL;DR
为什么 dir
名称中出现单引号?是 datetime __str__
或 __repr__
函数的问题吗?
您的目录名可能没有引号。它只是这样显示的。尝试将 space 添加到您的 strftime
示例中,看看会发生什么:
os.mkdir(f'{datetime.now().strftime("%Y-%m-%d_%I %M-%S_%p")}')
见Why is 'ls' suddenly wrapping items with spaces in single quotes?