Jecki
Jecki

Reputation: 802

Python create folders structure based on current date

i'm using the following var on my script to send output to one

output = "/opt/output"

i want to adjust it to make the output relative to the date current date of trigger the script it should be structured like this

output = "/opt/output/year/month/day"

i'm not sure if i'm using the correct way here i used the following approach

output = "/opt/output/" + today.strftime('%Y%m%d')

any tips here

Upvotes: 1

Views: 8871

Answers (4)

Jecki
Jecki

Reputation: 802

i figure it by

today = datetime.datetime.now()
year = today.strftime("%Y")
month=today.strftime("%m")
day=today.strftime("%d")
output = "/opt/output/"  + year +"/" + month + "/" + day

thats worked fine to me

Upvotes: 2

user6165050
user6165050

Reputation:

I recommend you use the full timestamp instead of just using the date:

import os

mydir = os.path.join(output, datetime.datetime.now().strftime('%Y/%m/%d_%H-%M-%S'))

It's recommended do it this way because what'd happen if your script runs more than once a day ? You should at least add a counter or something (if you don't want the full timestamp) which will increment some variable if the folder already exist.

You can read more about os.path.join here

As per creating a folder, you can do it like this:

if not os.path.exists(directory):
    os.makedirs(mydir)

Upvotes: 4

DeepSpace
DeepSpace

Reputation: 81604

I will suggest using os.path.join and os.path.sep:

import os 
.
.
.
full_dir = os.path.join(base_dir, today.strftime('%Y{0}%m{0}%d').format(os.path.sep))

Upvotes: 1

morfindel
morfindel

Reputation: 132

today.strftime('%Y%m%d') would print todays date as 20170607. But I guess you want it printed as 2017/06/07. You could explicitly add the slashes and print it something like this?

output = "/opt/output/" + today.year +"/" + today.month + "/" + today.date

Upvotes: 0

Related Questions