【问题标题】:create a file name with the current date & time in python在 python 中创建具有当前日期和时间的文件名
【发布时间】:2020-01-11 13:23:16
【问题描述】:

我使用datedime 在 Python 中创建一个目录名,如下所示:

代码:

import os
from datetime import datetime

os.mkdir(f"{datetime.now()}")
os.listdir()

当我在终端中使用ls 命令时,我得到了以下结果:

当我使用 Python 获得 dir 名称时:

代码:

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__ 函数有问题吗?

【问题讨论】:

    标签: python python-3.x datetime mkdir


    【解决方案1】:

    您的目录名称可能没有有引号。它只是以这种方式显示。尝试在您的 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?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-24
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      • 2017-05-04
      • 2014-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多