0

Suppose we have the following list of date objects:

['2021-09-21T17:27:23.654Z', '2021-09-21T18:31:57.560Z', '2021-09-21T20:36:14.125Z'].

How do we find which of these dates is the earliest and which is the latest? Is there a way to convert these dates to seconds?

When I do the following:

   dts_list = ['2021-09-21T17:27:23.654Z', '2021-09-21T18:31:57.560Z', '2021-09-21T20:36:14.125Z']
   dts = [datetime.fromisoformat(d) for d in dts_list]

I get the following error message:

  ValueError: Invalid isoformat string: '2021-09-21T18:31:57.560Z'
stackguy1723
  • 165
  • 1
  • 2
  • 12
  • 3
    Those are not date objects. Those are just strings, in ISO-8601 format. It just so happens that format allows you to compare the dates as simple strings, so no conversion is necessary. If you want to know the DELTA between them, then you'll need to convert them to `datetime.datetime` objects. – Tim Roberts Sep 30 '21 at 21:08
  • @TimRoberts: I tried converting the strings to date time objects but got the error mentioned in my post. – stackguy1723 Sep 30 '21 at 21:24

3 Answers3

2
import datetime

dates_str = ['2021-09-21T17:27:23.654Z', '2021-09-21T18:31:57.560Z', '2021-09-21T20:36:14.125Z']
date_format = '%Y-%m-%dT%H:%M:%S.%f%z'
dates = [datetime.datetime.strptime(date, date_format) for date in dates_str]

# comparing dates
print('comparison:', dates[0] < dates[1])

# finding the min/max dates in list
print('min date is:', min(dates))
print('max date is:', max(dates))

# finding the index for min/max dates in list
print('index for min is:', dates.index(min(dates)))
print('index for max is:', dates.index(max(dates)))

# converting to seconds
timestamps = [date.timestamp() for date in dates]
print('dates in seconds:', timestamps)
-1

This prints sorted list of python datetime objects.

from datetime.datetime import fromisoformat

times = ['2021-09-21T17:27:23.654Z', '2021-09-21T18:31:57.560Z', '2021-09-21T20:36:14.125Z']

# drop the 'Z' at the end
print(sorted([fromisoformat(time[:-1]) for time in times]))
-1

You should start by converting them to datetime.datetime objects, like so:

from datetime import datetime

dts_list = ['2021-09-21T17:27:23.654Z', '2021-09-21T18:31:57.560Z', '2021-09-21T20:36:14.125Z']
# Does not account for time zones...
dts = [datetime.fromisoformat(d.strip('Z')) for d in dts_list]

Then, you can use the objects to compare their data:

print(dts[0].second < dts[1].second)
# True
Xiddoc
  • 3,369
  • 3
  • 11
  • 37
  • 1
    Just to be stubborn, I need to point out that `dts_list[0] > dts_list[1]` also works using the original strings. To do any further analysis, you'd want the objects, but for finding min and max, the strings work equally well. – Tim Roberts Sep 30 '21 at 22:25
  • You're right, what was I thinking. I'll change it in a sec. – Xiddoc Oct 01 '21 at 05:05
  • @TimRoberts do you think that my edits improve my answer? – Xiddoc Oct 01 '21 at 08:01