Trouble understanding Bash and translating to Python

Question:

I am trying to translate this from Bash to Python:

export file="${directory}/scrutation_$(date "+%Y%m%d_%H%M%S").log"

I know that export sets an environment variable, and that (date "+%Y%m%d_%H%M%S") is strftime("%d/%m/%Y, %H:%M:%S") in Python.

This is what I have tried:

import os
os.environ[file]= f"{directory}/scrutation[strftime("%d/%m/%Y, %H:%M:%S")].log"

Is this correct?

Asked By: answer007

||

Answers:

The name of the environment variable is a string, it needs to be quoted.

Double quotes aren’t nested in f"", use single quotes for one of the pairs.

$(...) is the Command Substitution, i.e. you need to run the strftime, not include it in square brackets.

Also, you can use the same format string without changes, unless you really want to change the timestamp format.

os.environ['file'] = f'{directory}/scrutation_' 
    f'{datetime.now().strftime("%Y%m%d_%H%M%S")}.log'
Answered By: choroba
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.