Reputation: 25
I have a list of image timestamps in the format '20121002_1639' ('%Y%m%d_%H%M')
I want to create a function that takes in a list of these timestamps and excludes images taken between 1500(3:00pm) and 1700 (5:00pm). However When I try to just parse the %H%M portion of the string, it automatically assigns those datetimes to the date 19000101_1500 and 19000101_1700. So I need to create objects which contain just hours and minutes but are not associated with a date.
The pseudo code would be something like this:
import datetime as dt
# example datetime string
datestrings = ['20121002_1639', '20111101_1229', '20160424_1502', '20170328_1100']
Start_time = dt.datetime.strptime('1500', '%H%M')
End_time = dt.datetime.strptime('1700', '%H%M')
good_times = []
for time in datestrings:
if dt.datetime.strptime(time[9:13], '%H%M') is between(Start_time, End_time):
continue
else:
good_times.append(time)
Upvotes: 0
Views: 174
Reputation: 54168
You may use only the time part from the datetime
object, for that use the .time()
method. So you don't need to parse only a part of the given string, parse all and then take it's time part
too
datestrings = ['20121002_1639', '20111101_1229', '20160424_1502', '20170328_1100']
Start_time = dt.datetime.strptime('1500', '%H%M').time()
End_time = dt.datetime.strptime('1700', '%H%M').time()
good_times = []
for time in datestrings:
if not (Start_time <= dt.datetime.strptime(time, '%Y%m%d_%H%M').time() < End_time):
good_times.append(time)
print(good_times) # ['20111101_1229', '20170328_1100']
In fact you coud even do it with basic int
comparisons
Start_time = 1500
End_time = 1700
for time in datestrings:
if not (Start_time <= int(time.split("_")[-1]) < End_time):
good_times.append(time)
Upvotes: 1