首页 > 解决方案 > 在 Python 中比较日期对象

问题描述

假设我们有以下日期对象列表:

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

我们如何找到这些日期中最早的日期和最晚的日期?有没有办法将这些日期转换为秒?

当我执行以下操作时:

   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]

我收到以下错误消息:

  ValueError: Invalid isoformat string: '2021-09-21T18:31:57.560Z'

标签: pythonpython-3.xdatetime

解决方案


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)

推荐阅读