myusuf3 / delorean

Delorean: Time Travel Made Easy
http://delorean.rtfd.org/
MIT License
1.84k stars 128 forks source link

Issues Handling Parse of iso8601 datetime strings #53

Open myusuf3 opened 9 years ago

myusuf3 commented 9 years ago
GOOD (precise offset): '2015-02-04T16:33:21.247513-05:00'
GOOD (precise utc indication): '2013-09-30T15:34:00.000Z'
BAD (no offset): '2015-02-04T16:33:21.247513'

Currently delorean parse function casts the bad (no timezone) version of the to utc.

Although there is no way to know whether or not the UTC was provided like in the 2nd good option or it was a decision (assumption) made my delorean internally (I blame my OCD).

Give a way to introspect this would be ideal. I would like to avoid providing naive datetimes being return by delorean but maybe a way to determine if assumptions were made.

Like so currently

>>> parse('2015-02-04T16:33:21.247513')
Delorean(datetime=2015-02-04 16:33:21.247513+00:00, timezone=UTC)
>>> parse('2015-02-04T16:33:21.247513').naive()
datetime.datetime(2015, 2, 4, 16, 33, 21, 247513)

Maybe this

>>>parse('2015-02-04T16:33:21.247513')
(True,Delorean(datetime=2015-02-04 16:33:21.247513+00:00, timezone=UTC))
>>> assumed, datetime = parse('2015-02-04T16:33:21.247513').naive()
>>> datetime
datetime.datetime(2015, 2, 4, 16, 33, 21, 247513)
myusuf3 commented 9 years ago

@rwarren Thoughts?

rwarren commented 9 years ago

Not a fan of the tuple return. I think I have a solution that enables me to not have to venture outside of the delorean for handling naive times, though. It works like this:

>>> from delorean import parse
>>>
>>> # Offset specified normalizes to UTC...
>>> parse("2015-02-04T16:33:21.247513-05:00")
Delorean(datetime=2015-02-04 21:33:21.247513+00:00, timezone=UTC)
>>>
>>> # UTC explicitly stated (with Z suffix) is also directly UTC...
>>> parse("2015-02-04T21:33:21.247513Z")
Delorean(datetime=2015-02-04 21:33:21.247513+00:00, timezone=UTC)
>>>
>>> # default behaviour with parse of naive times stays status quo (norm to UTC)...
>>> parse("2015-02-04T21:33:21.247513")
Delorean(datetime=2015-02-04 21:33:21.247513+00:00, timezone=UTC)
>>>
>>> # ...unless you *tell* delorean to keep it naive (note datetime return)...
>>> parse("2015-02-04T21:33:21.247513", naivemode="naive")
datetime.datetime(2015, 2, 4, 21, 33, 21, 247513)
>>>
>>> # ... or you can (of course) explicitly state the default behaviour (norm to utc)...
>>> parse("2015-02-04T21:33:21.247513", naivemode="utc")
Delorean(datetime=2015-02-04 21:33:21.247513+00:00, timezone=UTC)
>>>
>>> # ...or you can tell it to bark at naive times...
>>> parse("2015-02-04T21:33:21.247513", naivemode="raise")   #BAD
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "delorean/interface.py", line 52, in parse
    raise DeloreanInvalidDatetime("Unable to determine timezone info")
DeloreanInvalidDatetime: Unable to determine timezone info

What do you think? This is up and working. I'll send a PR.