Setting up Folders Named as Today's Date

The following brief snippet of code generates Today’s date as a string. The string it generates can be appended to the end of a filename, for example, to serve as a timestamp for pieces of code that are run only every several days.

from datetime import date

d = (str(date.today().year) + '-' +
     str(date.today().month).zfill(2) + '-' +
     str(date.today().day).zfill(2))
print(d)
2021-04-23

It could also be used to programmatically create a directory using the os module.

from datetime import date
import os

d = (str(date.today().year) + '-' +
     str(date.today().month).zfill(2) + '-' +
     str(date.today().day).zfill(2))
print(d)

if not os.path.exists('test_dirs'):
    os.mkdir('test_dirs')
os.mkdir('test_dirs/' + d)
2021-04-23

The following bash command prints all directories in the test_dirs directory. Sourced from here.

%%bash
cd test_dirs
ls -d -- */
2021-04-23/

The following useful script creates a folder with today’s date, or if a folder with that name already exists, it creates one with a sequential integer appended, like 2021-04-23_01.

from datetime import date
import os

def create_date_dir():
    i = 0
    d = (str(date.today().year) + '-' +
         str(date.today().month).zfill(2) + '-' +
         str(date.today().day).zfill(2))

    if not os.path.exists('test_dirs'):
        os.mkdir('test_dirs')

    while os.path.exists('test_dirs/' + d):
        i += 1
        d = d[:10] + '_' + str(i).zfill(2)
    os.mkdir('test_dirs/' + d)

Following command runs create_date_dir another three times.

for _ in range(3):
    create_date_dir()

The following bash command prints all directories in the test_dirs directory. Sourced from here.

%%bash
cd test_dirs
ls -d -- */
2021-04-23/
2021-04-23_01/
2021-04-23_02/
2021-04-23_03/