1

Possible Duplicate:
Parse date and format it using python?

I'm very new to Python. I have the following two strings :

Mon, 29 Oct 2012 13:07:07 GMT
2012-10-29 12:57:08

I wish there could be any date parsing lib available in python which does parse the above two strings to something like this:

2012-10-29 12:57:08

So that I can compare them. Note that the comparison should be able to produce the result like integer comparison. Like 1 is less than 2, so the same way 2012-10-29 12:57:08 is less than 2012-10-29 13:57:08

Are there any easy to do so in python?

Thanks in advance.

1

3 Answers 3

7

Use the dateutil module for general date parsing:

>>> from dateutil.parser import parse
>>> parse('Mon, 29 Oct 2012 13:07:07 GMT')
datetime.datetime(2012, 10, 29, 13, 7, 7, tzinfo=tzutc())
>>> parse('2012-10-29 12:57:08')
datetime.datetime(2012, 10, 29, 12, 57, 8)

datetime.datetime objects can be compared in various ways.

If you know the exact format of each date string to be parsed, you can also do the parsing more explicitly using the datetime.datetime.strptime() method:

>>> import datetime
>>> datetime.datetime.strptime('Mon, 29 Oct 2012 13:07:07 GMT', '%a, %d %b %Y %H:%M:%S %Z')
datetime.datetime(2012, 10, 29, 13, 7, 7)

Note however that that method ignores timezones!

Sign up to request clarification or add additional context in comments.

2 Comments

+1 That works. But how do I compare the two result in order to find which one is smaller or greater?
@GroovyUser: Like you would other values: dt1 < dt2, etc. Note that you may want to remove the timezone and/or cast everything to UTC first (dt1.astimezone(datutil.tz.tzutc()) for datetime objects with a timezone, dt2.replace(tzinfo=dateutil.tz.tzutc()) for those without, or use the default keyword to parse to give all parsed datetime objects a timezone even if the string is missing timezone info. Removing a timezone is done with .replace(tzinfo=None)).
2

Yes, time.strptime can convert the text to date representations. From there you can use strftime to print it how you like.

>>> a = '2012-10-29 12:57:08'
>>> time.strptime(a, '%Y-%m-%d %H:%M:%S')
time.struct_time(tm_year=2012, tm_mon=10, tm_mday=29, tm_hour=12, tm_min=57, tm_sec=8, tm_wday=0, tm_yday=303, tm_isdst=-1)
>>> b = 'Mon, 29 Oct 2012 13:07:07 GMT'
>>> time.strptime(b, '%a, %d %b %Y %H:%M:%S %Z')
time.struct_time(tm_year=2012, tm_mon=10, tm_mday=29, tm_hour=13, tm_min=7, tm_sec=7, tm_wday=0, tm_yday=303, tm_isdst=0)

Comments

1

The datetime module in python, with its strptime function (string parse), can do that.

For example, you can use the function like this:

somestring = '2004-03-13T03:00:00Z'
result = datetime.datetime.strptime(somestring, '%Y-%m-%dT%H:%M:%SZ')

Docs here.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.