简体   繁体   中英

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.

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.

You can convert the string to datetime using strptime in conjunction with the relevant format . 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:

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. If you want to ditch the current time, replace the 'time' or 'xvar' variables with a string. 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

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.

My solution: a function that takes a string time and hour param to determine which messages to delete. (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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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