Adding a timestamp to a file, python subprocess linux
Question: I’m trying to take a picture with my `Raspicam` on my raspberry and adding a
`timestamp` too each picture. The code that I use doesn’t however work. It
gives me a syntax error at `.."+%H...` I have mucked around in the code and
was able too do it once, then tough the picture file didn’t receive any
`timestamp` on it.

Does any one have any clue what im doing wrong?

    
    
    #!/usr/bin/python
    
    import RPi.GPIO as GPIO, time, os, subprocess, random
    
    gpout = subprocess.check_output("stamp=$(date "+%H%M%S")", stderr=subprocess.STDOUT,shell=True)
    
    gpout = subprocess.check_output("raspistill -t 1 --output /home/pi/photobooth_images/Test${stamp}.jpg", stderr=subprocess.STDOUT, shell=True)
    


Answer: There are at least two issues:

  * to use double quotes inside a Python string literal, you should escape them or use single quotes for the string literal:
    
        'stamp=$(date "+%H%M%S")'
    

  * it is pointless to set `stamp` shell variable because `check_output()` call spawns its own shell i.e., `stamp` won't be defined in the second command where you are trying to use it

You could emulate `date "+%H%M%S"` in Python:

    
    
    import time
    from subprocess import check_output, STDOUT
    
    timestamp = time.strftime('%H%M%S')
    path = '/home/pi/photobooth_images/Test{stamp}.jpg'.format(stamp=timestamp)
    gpout = check_output(["raspistill", "-t", "1", "--output", path], stderr=STDOUT)
    

Note: `shell=True` is not used.

You could also format an existing datetime object:

    
    
    from datetime import datetime
    
    path = '/path/to/Test{now:%H%M%S}.jpg'.format(now=datetime.now())
    

