I have list of links and have extracted the timestamp from the link and put at the start of each element of the list. In total 478 elements in the list.
[01:00:38 link1’, 01:01:38 link2’, … ‘23:57:39 link478’]
I now want to be able to slice the list based on the timestamp. So for example if I wanted only to extract a time range from 03:00 to 07:00. How could this be achieved ?
You could convert the time to an int and then select elements based on the int range.
For example 03:00 is 36060 seconds.
If your time strings are always well formed you can use string comparison.
time >= '03:00:00 and time < '07:00:00'
for example.
You can use a list comprehension to loop over the elements of your list and select the ones you need. See 5. Data Structures — Python 3.13.2 documentation
Hello,
if you want to extract elements from your list that fall within a certain lower and upper bound timestamps, you can try something like the following script:
# Arbitrary list for test purpose
list_of_links= [ '01:00:38 link1', '01:01:02 link1', '04:01:35 link1', '04:25:06 link1',
'05:08:44 link1', '06:12:14 link1', '06:17:51 link1', '02:38:24 link1']
# List to save qualified
timestamp_list = []
from datetime import datetime
# Create lower and upper timestamp time objects
time_lower_ref = datetime.strptime('03:00:00', "%H:%M:%S").time()
time_upper_ref = datetime.strptime('07:00:00', "%H:%M:%S").time()
# Loop through all the elements in your 'list of links'
for index in range(len(list_of_links)):
# Read each element and extract only the timestamp
date_string = list_of_links[index].split(" ")[0]
# Convert to time object
time_object = datetime.strptime(date_string, "%H:%M:%S").time()
# Compare each element with lower and upper boundaries
if time_object >= time_lower_ref and time_object <= time_upper_ref:
timestamp_list.append(list_of_links[index])
print(timestamp_list)
I have added comments so that you can follow along.
As is, you can replace your list into the test script and it should work.
Whan I ran the script, I got the following list:
['04:01:35 link1', '04:25:06 link1', '05:08:44 link1', '06:12:14 link1', '06:17:51 link1']
They’re all within the lower and upper timestamp boundaries.