简体   繁体   中英

Improperly creating timestamped filenames

I'm using a raspberry pi and a python script to capture images from a camera connected to the pi. I have a task scheduler that calls the script, and the script make a command line call that interfaces with the camera. I'm trying to have it create a new file titled with the timestamp taken from python's datetime module.

The problem I'm experiencing is that it won't print both. I can create a file with just the date timestamp; I can create one with just the time. When I try to combine both, however, the file isn't created, and I'm not sure why. Is it because the filename ends up being too long?

I've tried numerous variations of the code below:

import os

import time
import datetime

ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime("%y-%m-%d_%H:%M:%S")

sys_call = 'fswebcam -r 1280x720 /home/pi/python/projectx_images/%s' %st

os.system(sys_call)

I've also tried using datetime.now() to no avail. Specifically, if I try either st = datetime.datetime.fromtimestamp(ts).strftime("%y-%m-%d') or st = datetime.datetime.fromtimestamp(ts).strftime("%H:%M:%S') then it works fine, but not with both.

Perhaps using Python is overkill here. Since your task scheduler is probably already invoking a shell when it invokes Python, let's just have the shell do the work.

Use this command for your command scheduler:

fswebcam -r 1280x720 /home/pi/python/projectx_images/$(date +%Y-%m-%d_%H:%M:%S)

Assuming...

st = datetime.datetime.fromtimestamp(ts).strftime("%y-%m-%d_%H:%M:%S') <--- close with " instead of '

isn't your problem... I've used the following code and it works for me.

ti = datetime.datetime.utcfromtimestamp(time.time()).strftime("%y-%m-%d_%H:%M:%S")

outputs...

'17-11-18_01:47:48'

Note: This outputs in UTC +0:00 so you'd need to apply another operation on it to get it to your timezone. Since time.time() returns a UNIX epoch time in seconds, you'd need to offset the time by however much faster/slower your timezone is, in relation to UTC +0:00, in seconds.

Ie if you're in EST time, then you'd apply utcfromtimestamp() on time.time() - 18000 to get the time for your timezone.

ti = datetime.datetime.utcfromtimestamp(time.time() - 18000).strftime("%y-%m-%d_%H:%M:%S")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM