Nick Peluso Nick Peluso - 3 months ago 30
Python Question

Python date comparison with string output/format

I'm currently trying to writing a script to automate a function at work, but I'm not intimately familiar with Python. I'm trying to take a XML dump and compare a specific entry's date to see if the time has passed or not.

The date is in a particular format, given:

<3-letter Month> <DD> <HH:MM:SS> <YYYY> <3-letter Timezone>

For example:

May 14 20:11:20 2014 GMT

I've parsed out a string in that raw form, and need to somehow compare it with the current time to find out if the time has passed or not. That said, I'm having a bit of trouble figuring out how I should go about either formatting my text, or choosing the right mask/time format in Python.

I've been messing around with different variations of the same basic format:

if(trimmed < time.strftime("%x") ):

Trimmed is the clean date/time string. Time is derived from import time.

Is there a simple way to fix this or will I have to dig into converting the format etc.? I know the above attempt is simplistic, but I'm still very new to Python. Thanks for your time and patience!


You should use combination of gmtime (for GMT time),mktime and datetime.

from time import gmtime,mktime
from datetime import datetime

s = "May 14 20:11:20 2014 GMT"
f = "%b %d %H:%M:%S %Y GMT"
dt = datetime.strptime(s, f)
gmt = datetime.fromtimestamp(mktime(gmtime()))
if dt<gmt: