Capture camera snapshot with timestamp using python_script

A short python_script to capture an image from a camera (here a raspberry pi camera) using the new snapshot service and save with a filename of the format 2017_11_5_20_45_7_779431.jpg

"""
Capture a timestamped camera image using the service camera.snapshot.
"""
now = datetime.datetime.now()
time = "{}_{}_{}_{}_{}_{}_{}".format(
    now.year, now.month, now.day, now.hour,
    now.minute, now.second, now.microsecond)

folder = '/home/pi/.homeassistant/camera_captures/'
filename = folder + time + '.jpg'

hass.services.call(
    'camera', 'snapshot',
    {'entity_id': 'camera.raspberry_pi_camera',
     'filename': filename})
2 Likes

Thanks for this, works well.

Are you using this with a shell command to action it in HASS? I can get this working calling the python script service but nothing happens using a shell command.

snapshot: python3 /home/homeassistant/.homeassistant/python_scripts/snapshot.py

Pasting the command in to terminal produces the following error:

python3 /home/homeassistant/.homeassistant/python_scripts/snapshot.py Traceback (most recent call last): File "/home/homeassistant/.homeassistant/python_scripts/snapshot.py", line 4, in <module> now = datetime.datetime.now() NameError: name 'datetime' is not defined

New python scripts so not sure If I’ve done something wrong my end?

Think I’m just using a regular script to call the python_script, which gives me a button on the front end.
On holidays now :sunglasses:

Is there a way to do this from inside a script? I want to store the image, and also keep the filename for a notification that I want to send.

I suppose you could write the filename to a dummy sensor and then use it in a script. Cheers

OK I updated the script to include making a notification with the filename and the file, requires using a sleep

"""
Capture a timestamped camera image using the service camera.snapshot.
"""
now = datetime.datetime.now()
time_str = "{}_{}_{}_{}_{}_{}_{}".format(
    now.year, now.month, now.day, now.hour,
    now.minute, now.second, now.microsecond)

folder = '/config/www/front_door_'
filename = folder + time_str + '.jpg'

hass.services.call(
    'camera', 'snapshot',
    {'entity_id': 'camera.driveway_dericam',
     'filename': filename})

## We need to wait for this file to be created before sending to notify
time.sleep(3)

hass.services.call(
    'notify', 'pushbullet_robin', {
        "message": "File saved : " + filename,
        "title": "front door notification",
        "data": {"file": filename}
    })
2 Likes

@robmarkcole thanks for your script… is it possible to do 3 snapshots in a row and send them all in one and the same notification? I am struggeling in changing your script… :frowning:

That sounds complicated, better to just call this script 3 times