简体   繁体   中英

In Python how to convert a string to a date and check if it is earlier than 5 mins

I have a string coming in as 5/4/2017 2:13:04 PM It is in utc timezone. I need to check if it is earlier than 5 mins. So I tried the following code.

statustime="""5/4/2017 2:13:04 PM"""
statustimefrm= datetime.strptime(statustime, "%m/%d/%Y %H:%M:%S %p") 
print "Input time "+str(statustimefrm)
print "Current time "+str(datetime.utcnow())
if statustimefrm < datetime.utcnow() + timedelta(seconds = -300):
    print "disconnected longer than 5 mins"
else:
   print "just disconnected wait"

The output is

Input time 2017-05-04 02:13:04
Current time 2017-05-04 14:16:23.147151
disconnected longer than 5 mins

when it is converting

statustimefrm= datetime.strptime(statustime, "%m/%d/%Y %H:%M:%S %p") 

looks like it is not taking the PM into account. When looking at the docs %p is for AM/PM. So why is it not working?

You need to change your %H into %I :

statustimefrm= datetime.strptime(statustime, "%m/%d/%Y %I:%M:%S %p") 

When you use strptime %p will only work if %I is used in the hour field.

If you're just trying to check if a difference is greater, and you're checking it, say, less than every hour, could you just check a few characters from that string?

statustime="""5/4/2017 2:13:04 PM"""

if abs(int(statustime[11:13]))>=5:
    print "disconnected longer than 5 mins"
else:
   print "just disconnected wait"

You'll need to put a sum in there eg statustime-current time. This may just be beginner naiivety, but seems like a simpler solution?

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