Search code examples
pythonpython-3.xdatetimemkdir

create a file name with the current date & time in python


I used datedime to create a directory name in Python like this:

Code:

import os
from datetime import datetime

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

And when I use ls command in terminal, I got the following result:

enter image description here

And when I got dir names with Python:

Code:

os.listdir()

Output:

['.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']

Solution:

I solved it with strftime() method:

Code:

import os
from datetime import datetime

os.mkdir(f'{datetime.now().strftime("%Y-%m-%d_%I-%M-%S_%p")}')

enter image description here


TL;DR

Why single quotes appear in dir name? Is it a problem from datetime __str__ or __repr__ functions?


Solution

  • Your directory name probably doesn't have quotes. It's just displayed that way. Try adding a space to your strftime example and see what happens:

    os.mkdir(f'{datetime.now().strftime("%Y-%m-%d_%I %M-%S_%p")}')
    

    See Why is 'ls' suddenly wrapping items with spaces in single quotes?