Python 如何正确比较两个日期时间变量?
我想比较两个datetime变量来检测当前时间是否在周末时间 我的代码在这里:Python 如何正确比较两个日期时间变量?,python,datetime,Python,Datetime,我想比较两个datetime变量来检测当前时间是否在周末时间 我的代码在这里: 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
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
正如我所知,条件1应该是正确的,而不是错误的。我该如何更正这个结果呢?你的
it[0]
的时区是-05:51
,所以当现在交易的时区是-05:00
时,将其与it[0]
进行比较,现在交易的时区变成有效的2018-09-10 21:50:59.001475
减去分钟,等于20:59:59.001475-05:51
,小于it[0]
的2018-09-10 21:00:00-05:51
,导致条件it[0]的False
,为什么不使用类似于'date.weekday(datetime.now(tz=trading\u时区))==5或date.weekday(datetime.now(tz=trading\u时区))==6`。时区-05:51
可能出错。这样的时区在现实中并不存在。产生DATETIME值的代码可能包含一个问题。您可以考虑使用一个库,如<代码>箭头< /代码>,这使得更容易在不同时区之间移动一段时间。现在我知道问题在哪里。如何更正从-05:51到-05:00的时间?我发现在datetime属性中设置时区时存在一些问题,例如:datetime(year=2018,month=9,day=11,hour=1,minute=15,second=0,tzinfo=trading\u timezone)
我使用localize()
来设置时区,结果是正确的:trading\u timezone.localize(日期时间(年=2018,月=9,日=11,小时=1,分钟=15,秒=0))
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
it[0] = it[0].replace(tzinfo=now_trading_timezone.tzinfo)