python - 在 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'
解决方案
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)
推荐阅读
- excel - 使用 VBA 读取文本行的特定部分
- python-3.x - Tkinter 按钮在切换窗口时失去回调(类实现)(python 3.X)
- ruby-on-rails - Rails 嵌套表单未插入数据库(oracle)
- python - AttributeError:“unicode”对象没有属性 XXX
- android - Gson 返回空值
- c++ - 无法在 CMAKE 项目中使用 XercesC
- go - Prometheus 类型收集器 - 如何用我自己的数据提供地图
- css - 如何在 AngularJS 前端启用/禁用选项卡
- dotnetnuke - 如何触发 DNN 中的站点地图提供程序来创建新站点地图?
- linux - 如何搜索模式从一行开始并在另一行结束?