Creating a new folder with a datetime

Viewed 27

I want to create a new folder using the current datetime, but I get an error:

import datetime
import os
x = datetime.datetime.now()
os.mkdir(x)

Error:

Traceback (most recent call last):
  File "c:\Users\sepeh\Desktop\F-1\mkdir.py", line 6, in <module> 
    os.mkdir(x)
TypeError: mkdir: path should be string, bytes or os.PathLike, not datetime
1 Answers

A good format for date designations is YYYYMMDDHHMMSS.

This format makes sure the files are displayed in chronological order when a directory listing is done. Always having zero-padded decimal numbers for month, day, hours, minutes, and seconds is important to maintain the sorting.

To get a string from datetime in this format it would look like:

datetime.datetime.now().strftime("%Y%m%d%H%M%S")

For creating the file, I would recommend using the Python pathlib

An example of putting this all together would be:

import datetime
from pathlib import Path

Path(datetime.datetime.now().strftime("%Y%m%d%H%M%S")).mkdir()

If that directory name is hard to read then the numbers can be split with some formatting. For example:

Path(datetime.datetime.now().strftime("%Y_%m_%dT%H-%M-%S")).mkdir()

Related