Home > other >  Comparing date objects in Python
Comparing date objects in Python

Time:10-01

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'

CodePudding user response:

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

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 compare them directly:

print(dts[0] > dts[1])
# False

CodePudding user response:

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)

CodePudding user response:

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]))
  • Related