0

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!

2
  • What is in trimmed? If (as it appears) time has an actual time value in it, why not make a time value from what you have parsed, and compare that to time? Commented Sep 21, 2016 at 14:24
  • Ahh sorry! Trimmed is the tag free formatted date/time entry. Time is derived directly from the standard library time. I'll edit accordingly. Commented Sep 21, 2016 at 15:15

1 Answer 1

1

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:
    print(dt)
else:
    print(gmt)
Sign up to request clarification or add additional context in comments.

4 Comments

You can use %Z instead of 'GMT' for more flexibility
To clarify, dt is the newly formatted date time string and gmt is the relative time from epoch to dt - right?
I changed some superficial things around for my output, but thanks a lot! Its functionally exactly what I was looking for!
No, here dt is a datetime.datetime() type var, parsed from string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.