Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get earliest and latest times from a list of datetimes

I have,

timestamp=[]
for x in model_obj:
     timestamp.append(x.start_time)

print timestamp

RESULT:

[datetime.datetime(2014, 9, 2, 19, 40, 1, tzinfo=<UTC>), datetime.datetime(2014, 9, 2, 19, 40, 14, tzinfo=<UTC>), datetime.datetime(2014, 9, 2, 19, 40, 7, tzinfo=<UTC>), datetime.datetime(2014, 9, 2, 21, 53, tzinfo=<UTC>), datetime.datetime(2014, 9, 2, 22, 25, 24, tzinfo=<UTC>), datetime.datetime(2014, 9, 2, 22, 2
5, 52, tzinfo=<UTC>)]

My question is: How to get the earliest and latest times from this list of datetimes in python?

like image 228
BLACK PANTHER Avatar asked Apr 14 '15 08:04

BLACK PANTHER


1 Answers

Use the built-in min()/max() functions:

earliest = min(timestamp)
latest = max(timestamp)

As side note I suggest you to build the list with the list comprehension:

timestamp = [x.start_time for x in model_obj]

UPDATE: The earliest representable datetime is 0001-01-01 00:00:00 so as far as I understand the 0000-00-00 date can't be loaded from database and you get the None in the x.Date_Time_End field.

The question is: does your task allow you to ignore this datetime? If yes then just filter out None values from the list:

end = [x.Date_Time_End for model2_obj if x.Date_Time_End]
end_time = max(end)
like image 52
catavaran Avatar answered Sep 28 '22 16:09

catavaran