【发布时间】:2018-12-25 21:43:36
【问题描述】:
我遇到了奇怪的 Python 日期时间比较问题。我得到两个字符串格式的日期时间(来自 REST 调用,JSON)开始日期时间和结束日期时间。我必须比较当前日期时间,如果它在这个范围内(开始日期时间和结束日期时间)采取一些行动。众所周知,这些日期的时区是美国/东部(美国北卡罗来纳州)。这是代码,
from pytz import timezone
from datetime import datetime
def main():
# All the dates are in US/Eastern time zone. Time zone for USA, North Carolina
# These dates are received from REST call in JSON
# I need to compare the current date time, if that falls within this range take some action
start_date_str = "7/17/2018 11:30:00 AM"
end_date_str = "7/17/2018 2:30:00 PM"
# To simulate current date time within the range, I will update the current date time value.
current_est_time = datetime.now(tz=timezone('US/Eastern'))
current_est_time = current_est_time.replace(year=2018, month=7, day=17, hour=12, minute=26)
print current_est_time
start_date = datetime.strptime(start_date_str,"%m/%d/%Y %I:%M:%S %p").replace(tzinfo=timezone('US/Eastern'))
end_date = datetime.strptime(end_date_str, "%m/%d/%Y %I:%M:%S %p").replace(tzinfo=timezone('US/Eastern'))
print start_date <= current_est_time <= end_date
if __name__ == '__main__':
main()
如果分钟值为 26,则比较打印 True,如果是 25,则打印 False。
上述代码示例的输出是
2018-07-17 12:26:06.646643-04:00
True
如果将 current_est_time 变量的分钟值更改为 25,则输出为2018-07-17 12:25:16.582573-04:00 False
有人可以帮我吗,我哪里出错了?
【问题讨论】:
-
您能提供您最近一次参加的考试吗?带输入/输出。
-
上述代码示例的输出为 2018-07-17 12:27:34.806142-04:00 True。如果将 current_est_time 变量的分钟值更改为 25,则输出为 2018-07-17 12:25:16.582573-04:00 False
-
代码对你有用吗???
-
嗨 Inder,请查看我的最新回答。
标签: python python-2.7 python-2.x python-datetime pytz