python日期比较_python 时间比较方法总结

1,最近发现,python的datetime可以直接运用比较运算符进行大小比较

首先定义一组9月份日期数组

from datetime import datetime

targets = [ # 9/1到9/30的日期数据数组

datetime.datetime(2020, 9, 1, 0, 0),

datetime.datetime(2020, 9, 2, 0, 0),

datetime.datetime(2020, 9, 3, 0, 0),

datetime.datetime(2020, 9, 4, 0, 0),

datetime.datetime(2020, 9, 5, 0, 0),

# (中间省略)

datetime.datetime(2020, 9, 25, 0, 0),

datetime.datetime(2020, 9, 26, 0, 0),

datetime.datetime(2020, 9, 27, 0, 0),

datetime.datetime(2020, 9, 28, 0, 0),

datetime.datetime(2020, 9, 29, 0, 0),

datetime.datetime(2020, 9, 30, 0, 0)

]

然后定义想要打印的日期范围

from_dt = datetime(2020, 9, 10)

to_dt = datetime(2020, 9, 20)

然后以开始日 <= 判断datetime对象 <= 结束日的形式运用比较运算符

for target in targets:

if from_dt <= target <= to_dt: # 小于等于9/20,大于等于9/10

print target

# 結果:

# 2020-09-10 00:00:00

# 2020-09-11 00:00:00

# 2020-09-12 00:00:00

# 2020-09-13 00:00:00

# 2020-09-14 00:00:00

# 2020-09-15 00:00:00

# 2020-09-16 00:00:00

# 2020-09-17 00:00:00

# 2020-09-18 00:00:00

# 2020-09-19 00:00:00

# 2020-09-20 00:00:00

你可能感兴趣的:(python日期比较)