如何正确比较两个日期时间变量?

我想比较两个日期时间变量来检测当前时间是否在周末时间。


我的代码在这里:


def is_weekend_off(weekend_table, trading_timezone):

    now_trading_timezone = datetime.now(tz=trading_timezone)

    is_weekend = False

    for it in weekend_table:

        condition1 = it[0] <= now_trading_timezone

        condition2 = now_trading_timezone < it[1]

        condition3 = condition1 and condition2

        print('now = ' + str(now_trading_timezone))

        print('it[0] = ' + str(it[0]))

        print('it[1] = ' + str(it[1]))

        print('condition1 = ' + str(condition1))

        print('condition2 = ' + str(condition2))

        time.sleep(60)

        if condition3:

            tmp = True

        else:

            tmp = False

        is_weekend = is_weekend or tmp

    return is_weekend

结果在这里:


now = 2018-09-10 21:50:59.001475-05:00

it[0] = 2018-09-10 21:00:00-05:51

it[1] = 2018-09-10 22:00:00-05:51

condition1 = False

condition2 = True

据我所知,condition1 应该是 True,而不是 False。我该如何纠正这个结果?


GCT1015
浏览 106回答 1
1回答

qq_笑_17

你it[0]有一个时区-05:51,所以当now_trading_timezone,他们的时区-05:00,进行比较it[0],now_trading_timezone变成有效的2018-09-10 21:50:59.001475减51分,等于20:59:59.001475-05:51,小于it[0]的2018-09-10 21:00:00-05:51,从而False为条件it[0] <= now_trading_timezone。要it[0]使用now_trading_timezone's更正's 的时区,您可以使用以下datetime.replace方法:it[0]&nbsp;=&nbsp;it[0].replace(tzinfo=now_trading_timezone.tzinfo)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python