python比较两个时间前后_Python:如何比较两个日期/时间?

I have the following two date/time which are date_time1 and date_time2 respectively:

2017-04-15 00:00:00

2017-04-17 15:35:19+00:00

parsed1 = dateutil.parser.parse(date_time1)

parsed2 = dateutil.parser.parse(date_time2)

and would if I were to receive another date/time called input_date_time (e.g. 2017-04-16 12:11:42+00:00), would like to do the following:

# Would like to check if `input_date_time` is within the range

if parsed1 <= input_date_time <= parsed2:

And got an error: TypeError: can't compare offset-naive and offset-aware datetimes

Thought up of breaking it down to just year, month, day, hour, minute, and second, and compare every single one.

What would be the proper way to do so?

解决方案

here is my edited (again) example

I think we should provide timezone data to every datetime object

assume that date_time1 is a local time.

I think we should add timezone data to date_time1 instead of clear other tzinfo (my first example)

import dateutil.parser

import datetime

from pytz import utc

date_time1 ='2017-04-15 00:00:00'

date_time2 ='2017-04-17 15:35:19+00:00'

input_date_time = '2017-04-16 12:11:42+00:00'

parsed1 = dateutil.parser.parse(date_time1).astimezone(utc)

parsed2 = dateutil.parser.parse(date_time2)

input_parsed = dateutil.parser.parse(input_date_time)

if parsed1 <= input_parsed <= parsed2:

print('input is between')

this can check if input is between parsed1 and parsed2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值