简体   繁体   English

将字符串转换为datetime,然后将其与datetime.now进行比较

[英]Converting string to datetime then comparing it with datetime.now

I want to take a string 我想带一个弦

"9:09am Jan 23"

and compare it with datetime.now() to get the amount of difference in hours only. 并将其与datetime.now()进行比较,以得出仅小时数之差。

So if I did something like 所以如果我做了类似的事情

now = datetime.datetime.now()
if now - (string in hours) > 24:
        return True
    else:
        return False

I've been messing with it for a little while and cant seem to successfully compare a string (or converted string object) with datetime.now. 我已经弄了一段时间,似乎无法成功地将字符串(或转换后的字符串对象)与datetime.now进行比较。

You can convert the string to datetime using strptime in conjunction with the relevant format . 您可以使用strptime结合相关格式将字符串转换为datetime。 You'll need to add the current year though: 不过,您需要添加当前年份:

import datetime
now = datetime.datetime.now()
year = now.year
datestring = "9:09am Jan 23 " + year
dt = datetime.datetime.strptime(datestring, "%H:%M%p %b %d %Y")

Subtracting two datetimes gives you a timedelta object, so you'll need to extract the days: 减去两个日期时间会得到一个timedelta对象,因此您需要提取日期:

diff = now - dt
days_diff = diff.days

Here is a function that will grab two instances of current time and return the difference in seconds. 这是一个将获取当前时间的两个实例并以秒为单位返回差值的函数。 This is done mostly with datetime's 'strptime', in which I convert the current time to strings. 这主要是通过datetime的“ strptime”完成的,我将当前时间转换为字符串。 If you want to ditch the current time, replace the 'time' or 'xvar' variables with a string. 如果要放弃当前时间,请用字符串替换'time'或'xvar'变量。 I used seconds here, but you can return hours of difference just as easily. 我在这里用了几秒钟,但是您可以轻松返回数小时的差异。

import datetime, sys

def time_passed():
    while True:
        inp = raw_input("Press [Y] to start, or [X] to exit.: ").lower()
        if inp == 'y':
            now = datetime.datetime.now()
            xvar = now.strftime("%b %d %H:%M:%S")
            time = datetime.datetime.strptime(xvar, "%b %d %H:%M:%S")
            time = time.replace(year = 2016)
            print "The first recording of the time is: {0}".format(time)
            print "The second recording of the time is: {0}".format(now)
            yvar = (now - time)
            print "Between the two times, there is a difference of {0} seconds".format(yvar.total_seconds())
            continue
        elif inp == 'x':
            sys.exit()
            break
        else:
            print "Command Error!"
            continue    

if __name__ == '__main__':
    time_passed()

Thanks for the help guys! 感谢您的帮助! What I wanted was how to compare the hours only, so I did a little hacking. 我想要的是仅比较小时数,因此我做了一些改动。 What I needed to do was get 我要做的就是得到

diff = now - dt diff =现在-dt

then to get the hours of that, which is what I was stuck on. 然后得到时间,这就是我坚持的时间。 The solution was to get the seconds of diff and divide by 3600. 解决的办法是获得diff的秒数并除以3600。

My solution: a function that takes a string time and hour param to determine which messages to delete. 我的解决方案:该函数需要一个字符串time和hour参数来确定要删除的消息。 (writing a web automation script) (编写网络自动化脚本)

def to_delete(self, date, accepted_range):
    """ decides to delete a message based on certain criteria """
    now = datetime.datetime.now()
    date_str = "%s %s" % (date, now.year)
    dt = datetime.datetime.strptime(date_str, "%H:%M%p %b %d %Y")
    diff = now - dt

    if diff.seconds/3600 > accepted_range:
        return True
    else:
        return False

It gives me the hours only and now I can delete posts if they're over x hours old 它只给我几个小时的时间,现在,如果它们超过x个小时,我就可以删除它们

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

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