I have a folder ("pictures") with many jpg.files with the filename as timestamp (e.g. "09_02_01.jp" or "10_04_01.jpg"). Now I want to iterate through the folder and all jpg files and use the filenames as timestamps. With these timestamps I want to check if some filenames (jpgs) are nearby. For e.g. if a timestamp of a picture is 09_02_01.jpg and another is 10_04_01.jpg I want to get the difference of the timestamps of the pictures and if the pictures difference is less than 30 seconds e.g. than I want to delete one of the pictures, because I only want one picture for every 30 seconds.
At the moment I only got the jpg filename convertet into a datetime format.
from datetime import datetime
import os
def gettime(folder_dir):
timediff_sec = 30
for images in os.listdir(folder_dir):
if images.endswith(".jpg"):
fn, fext = os.path.splitext(images)
# string name
timestamp1 = fn
# Convert String to datetime Object
t1 = datetime.strptime(timestamp1, "%H_%M_%S").time()
print(t1)
gettime("Bilder")
CodePudding user response:
You can try my code below:
from datetime import datetime
import os
def gettime(folder_dir):
timediff_sec = 30
time_stamps = []
for images in os.listdir(folder_dir):
if images.endswith(".jpg"):
fn, fext = os.path.splitext(images)
# string name
timestamp1 = fn
# Convert String to datetime Object
t1 = datetime.strptime(timestamp1, "%H_%M_%S")
t1 = datetime.timestamp(t1)
if len(time_stamps) == 0 or abs(int(t1) - min(time_stamps)) >= 30 or abs(int(t1) - max(time_stamps)) >= 30:
time_stamps.append(int(t1))
else:
os.remove(os.path.join(folder_dir, images))
gettime("Bilder")