50

I have a system (developed in Python) that accepts datetime as string in VARIOUS formats and i have to parse them..Currently datetime string formats are :

Fri Sep 25 18:09:49 -0500 2009

2008-06-29T00:42:18.000Z

2011-07-16T21:46:39Z

1294989360

Now i want a generic parser that can convert any of these datetime formats in appropriate datetime object...

Otherwise, i have to go with parsing them individually. So please also provide method for parsing them individually (if there is no generic parser)..!!

0

2 Answers 2

72

As @TimPietzcker suggested, the dateutil package is the way to go, it handles the first 3 formats correctly and automatically:

>>> from dateutil.parser import parse
>>> parse("Fri Sep 25 18:09:49 -0500 2009")
datetime.datetime(2009, 9, 25, 18, 9, 49, tzinfo=tzoffset(None, -18000))
>>> parse("2008-06-29T00:42:18.000Z")
datetime.datetime(2008, 6, 29, 0, 42, 18, tzinfo=tzutc())
>>> parse("2011-07-16T21:46:39Z")
datetime.datetime(2011, 7, 16, 21, 46, 39, tzinfo=tzutc())

The unixtime format it seems to hiccough on, but luckily the standard datetime.datetime is up for the task:

>>> from datetime import datetime
>>> datetime.utcfromtimestamp(float("1294989360"))
datetime.datetime(2011, 1, 14, 7, 16)

It is rather easy to make a function out of this that handles all 4 formats:

from dateutil.parser import parse
from datetime import datetime

def parse_time(s):
    try:
        ret = parse(s)
    except ValueError:
        ret = datetime.utcfromtimestamp(s)
    return ret
Sign up to request clarification or add additional context in comments.

2 Comments

actually this is what i already did, when @TimPietzcker suggested...u can see that in the comment..!!..but thanx for the awesome reply (and code description)..!!
To install dateutil: pip install python-dateutil. It's like they want you to think it's not a legit package when they don't offer how to install it via pip.
15

You should look into the dateutil package.

2 Comments

especially dateutil.parser.parse()
thanx for the answer..!!..but one thing.."dateutil.parser.parse" is parsing first 3 date formats..but it is not able to parse the last date format (which is a long value)..It is showing a "year out of range" Exception... But python inbuilt datetime module is able to parse this long value..why is it so..??

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.