简体   繁体   English

将 datetime.now() object 的时间与时间字符串进行比较

[英]Compare the time of datetime.now() object with time string

Using Rouble's suggestion and Maulik Gangani's example based on that suggestion:使用 Rouble 的建议和基于该建议的 Maulik Gangani 的示例:

How do I determine if current time is within a specified range using Python's datetime module? 如何使用 Python 的 datetime 模块判断当前时间是否在指定范围内?

I have two time strings that have been converted into a datetime object using.strptime as follows:我有两个时间字符串已使用 .strptime 转换为日期时间 object,如下所示:

timeStart = '0300'
timeStart = datetime.strptime(timeStart, '%H%M')

I have a datetime object for time now: timeNow = datetime.now()我现在有一个日期时间 object:timeNow = datetime.now()

My problem is that unless I convert timeNow (datetime object) into a string and then back again using.strptime, the script will not work:我的问题是,除非我将 timeNow(日期时间对象)转换为字符串,然后使用 .strptime 再次返回,否则脚本将无法运行:

timeNow = datetime.now()
timeNow = datetime.strftime(timeNow, '%H%M')
timeNow = datetime.strptime(timeNow, '%H%M')

Full code:完整代码:

from datetime import datetime

def isNowInTimePeriod(startTime, endTime, nowTime):
    if startTime < endTime:
        return nowTime >= startTime and nowTime <= endTime
    else: #Over midnight
        return nowTime >= startTime or nowTime <= endTime


timeStart = '0300'
timeEnd = '1000'

timeEnd = datetime.strptime(timeEnd, '%H%M')
timeStart = datetime.strptime(timeStart, '%H%M')
timeNow = datetime.now()
timeNow = datetime.strftime(timeNow, '%H%M')
timeNow = datetime.strptime(timeNow, '%H%M')

My question is, how do I format timeNow = datetime.now() so that I can compare it against a string in 24hr format '0000' without having to convert datetime.now() to a string and back again?我的问题是,如何格式化 timeNow = datetime.now() 以便我可以将它与 24 小时格式 '0000' 的字符串进行比较,而不必将 datetime.now() 转换为字符串然后再转换回来?

If you call datetime.strptime , a default date is added if you only supply a time string.如果您调用datetime.strptime ,如果您只提供时间字符串,则会添加默认日期。 datetime.now() will have today's date. datetime.now()将有今天的日期。 You can remove that by using only the time part of the datetime object - which you get by calling the time() method, eg您可以通过仅使用日期时间 object 的时间部分来删除它 - 您可以通过调用time()方法获得它,例如

from datetime import datetime

def isNowInTimePeriod(startTime, endTime, nowTime):
    if startTime < endTime:
        return nowTime >= startTime and nowTime <= endTime
    else: #Over midnight
        return nowTime >= startTime or nowTime <= endTime

timeStart = '0300'
timeEnd = '1000'

timeEnd = datetime.strptime(timeEnd, '%H%M').time()
timeStart = datetime.strptime(timeStart, '%H%M').time()
timeNow = datetime.now().time()

print(isNowInTimePeriod(timeStart, timeEnd, timeNow))
# True (my current time is 0823)

The reason why your code is not working, it's because apart from time, datetime (as the name suggests) holds also information about the date.您的代码之所以不起作用,是因为除了时间之外, datetime时间(顾名思义)还包含有关日期的信息。

When you run the following code:当您运行以下代码时:

timeStart = '0300'
timeStart = datetime.strptime(timeStart, '%H%M')

The hour and minute is converted, but the rest (the "date" part) is assumed to be epoch:小时和分钟被转换,但 rest(“日期”部分)被假定为纪元:

repr(timeStart)
# Output: 'datetime.datetime(1900, 1, 1, 3, 0)'

When you run datetime.now() , however, that always assumes the current time + date:但是,当您运行datetime.now()时,它总是假定当前时间 + 日期:

>>> datetime.now()
datetime.datetime(2020, 7, 17, 8, 25, 18, 270848)

The reason why converting to string, and back from string works, is because when you convert your datetime to a string with the format '%H%M , you lose the date part in the resulting string.转换为字符串并从字符串返回的原因是,当您将日期时间转换为格式为'%H%M的字符串时,您会丢失结果字符串中的日期部分。 Converting back from that, there's only hour and minutes to read, so you're losing the date part.从那里转换回来,只有小时和分钟可以阅读,所以你丢失了日期部分。

Effectivelly, you should be using datetime.time , instead of datetime.datetime to compare time.实际上,您应该使用datetime.time而不是datetime.datetime来比较时间。

After reading using strptime , try using the .time() method to only extract the time part and lose the date part:使用strptime阅读后,尝试使用.time()方法仅提取时间部分并丢失日期部分:

timeStart = '0300'
timeStart = datetime.strptime(timeStart, '%H%M').time()

And same for the timeNow part: timeNow部分也一样:

timeNow = datetime.now().time()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM