Aparna
Aparna

Reputation: 845

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?

Upvotes: 1

Views: 58

Answers (2)

toonarmycaptain
toonarmycaptain

Reputation: 2331

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?

Upvotes: 0

duncan
duncan

Reputation: 1161

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.

Upvotes: 2

Related Questions