Enric Agud Pique
Enric Agud Pique

Reputation: 1105

create folder in python with date YYYYMMDDHH

I am doing my first steps in python. I try to create a folder with the date with format YYYYMMDDHH

For example, today, 20170225HH, where HH should 00 if the real hour is between 00h-12h, and 12 if the real hour is between 12h-24h.

With the following code I create the folfer but I don't get 00 at 10:00h, I get 12:00?? Any help? I create a folder with name 2017022512 and I need 2017022500 at 10:00...thanks

#! usr/bin/python
import datetime
import time
import os

today=time.strftime('%Y%m%d')
hour=time.strftime('%h')
if(hour<12): h = "00"
else: h ="12"
os.system("mkdir /home/xxx/"+str(today)+""+str(h)+"")

Upvotes: 4

Views: 29991

Answers (2)

J Agustin Barrachina
J Agustin Barrachina

Reputation: 4090

Here is the solution using pathlib

from datetime import datetime
import os

today = datetime.now()   # Get date
datestring = today.strftime("%Y%m%d%H")  # Date to the desired string format
Path(datestring).mkdir(parents=True, exist_ok=True)   # Create folder

Using exist_ok avoids collisions if folder was already created. Works great when using multiple threds (running script in parallel).

Upvotes: 0

shashankqv
shashankqv

Reputation: 525

Use below code,

#! usr/bin/python
from datetime import datetime
import os

today = datetime.now()

if today.hour < 12:
    h = "00"
else:
    h = "12"

os.mkdir("/home/xxx/" + today.strftime('%Y%m%d')+ h)

Upvotes: 10

Related Questions