[Datetime-SIG] PEP-431/495

Guido van Rossum guido at python.org
Thu Aug 27 20:14:39 CEST 2015


On Thu, Aug 27, 2015 at 10:53 AM, Tim Peters <tim.peters at gmail.com> wrote:

> [...]
> Stewart, I still don't grasp what your problem is.  The only concrete
> example I've seen is dealing with this string:
>
>     2004-10-31 01:15 EST-05:00
>
> where you knew "EST" meant US/Eastern, but you haven't explained
> exactly what you're trying to _do_ with it.  If you're trying to
> create an aware datetime out of it in a post-PEP-495 pytz, then "the
> obvious" way is:
>
> 1. Create a UTC datetime out of "2004-10-31 01:15" alone.
> 2. Create timedelta(hours=-5) out of "-05:00" alone.
> 3. Subtract the result of #2 from the result of #1, to convert to UTC for
> real.
> 4. Invoke .astimezone() on the result of #3, passing pytz's spelling
> of "US/Eastern".


Funny, I would have done it this way (but the outcome should be the same):

1. Create a naive datetime out of "2004-10-31 01:15" alone.
2. Create timedelta(hours=-5) out of "-05:00" alone.
3. Subtract the result of #2 from the result of #1 to get the UTC time as a
naive datetime.
4. Use .replace(tzinfo=datetime.timezone.utc) to mark the result as UTC.
5. Invoke .astimezone() on the result of #3, passing pytz's spelling
of "US/Eastern".

Only #5 requires pytz (though you could use pytz.utc in #4 -- it doesn't
matter).

My reason for the extra step is philosophical: the datetime created in the
first step is just a (date, time) combo that *doesn't know* its timezone
yet. Only after step 3 do we have the designated point in time, so then we
can mark it as UTC.

Of course, since the result is the same, if Tim's version is faster that's
a fine way to do it -- but IMO mine makes it clearer what's going on.

-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/datetime-sig/attachments/20150827/43b3f6bd/attachment.html>


More information about the Datetime-SIG mailing list