the Gravity of Python 2

Chris Angelico rosuav at gmail.com
Wed Jan 8 23:03:45 EST 2014


On Thu, Jan 9, 2014 at 2:35 PM, Roy Smith <roy at panix.com> wrote:
>> Yes, it *is* simple. It *is* easy. I've been working with pure-UTC
>> times (either called time_t, or TIMESTAMP WITH TIME ZONE, or even just
>> float) for decades. Like with so many other things, the easiest
>> solution is also the best, because you can just work with one stable
>> representation and abstraction on the inside, with conversions to/from
>> it at the boundaries. It IS that easy.
>
> Please show me the simple code to obtain an aware UTC datetime
> representing the current time.

In Pike:
time();

In PostgreSQL:
SELECT now();

In C:
time(0);

All of these give a value in UTC. The PostgreSQL one gives it to you
as a TIMESTAMP WITH TIME ZONE, the others just as a simple value. I
don't know how they go about figuring out what UTC is, on systems
where the computer clock is in local time (eg Windows), but figure out
they do. It might be expensive but it's done somehow. (Easiest way to
check timezone in C is to look at what time(0)%86400/3600 is - that
should be the hour-of-day in UTC, which as I type is 3. And it is.)

I don't know how to do it in Python because I'm not familiar with the
datetime module. But time.time() returns a value in UTC, which is
verifiable by the above method:

>>> int(time.time())%86400//3600
3

So maybe the key is to use utcfromtimestamp()? I don't know. My
personal preference would be to simply use either int or float
everywhere (float if you need subsecond resolution, int if you're
concerned about massively past or future timestamps), and then
translate to something else for display. Effectively, instead of
working with a datetime object, I would just work with an alternative
representation of instant-in-time which is simply seconds since 1970
(dealing with leap seconds whichever way you like). If the datetime
module causes you pain, don't use it.

Ben, if it's that expensive to get an aware timestamp, why does
time.time() effectively do that? Is it a much more expensive call?

ChrisA



More information about the Python-list mailing list