1

I am trying to include the date in the name of a file. I'm using a variable called 'today'.

When I'm using bash I can reference a variable in a long string of text like this:

today=$(date +"%m-%d-%y")
output_dir="output_files/aws_volumes_list"
ofile="$output_dir"/aws-master-ebs-volumes-list-$today.csv

How can I achieve the same thing in python? I tried to do this, but it didn't work:

today = datetime.today()
today = today.strftime("%B %d %Y")
output_file = '../../../output_files/aws_instance_list/aws-master-list-'today'.csv'

I tried keeping the today variable out of the path by using single quotes.

How can I include the date in the name of the file that I'm creating when using Python?

asked Mar 7, 2019 at 22:23

5 Answers 5

3

You can add the strings together or use string formatting

output_file = '../../../output_files/aws_instance_list/aws-master-list-' + today + '.csv'
output_file = '../../../output_files/aws_instance_list/aws-master-list-{0}.csv'.format(today)
output_file = f'../../../output_files/aws_instance_list/aws-master-list-{today}.csv'

The last one will only work in Python>= 3.6

answered Mar 7, 2019 at 22:25
Sign up to request clarification or add additional context in comments.

Comments

1

In Python you use + to concat variables.

today = datetime.today()
today = today.strftime("%B %d %Y")
output_file = '../../../output_files/aws_instance_list/aws-master-list-' + today +'.csv'
answered Mar 7, 2019 at 22:25

Comments

1
answered Mar 7, 2019 at 22:29

Comments

1

Not quite sure if thats what you mean, but in python you can either simply add the strings together

new_string=str1+ str2

or something like

new_string='some/location/path/etc/{}/etc//'.format(another_string)
answered Mar 7, 2019 at 22:31

Comments

1

The closest Python equivalent to bash's

ofile="$output_dir"/aws-master-ebs-volumes-list-$today.csv

is

ofile=f'"{output_dir}"/aws-master-ebs-volumes-list-{today}.csv'

Only in Python 3.7 onwards.

answered Mar 7, 2019 at 22:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.