[python-win32] how to best use datetime objects in pywin32?

Mark Hammond mhammond at skippinet.com.au
Wed Jan 14 04:07:43 CET 2009


Thanks for the comments Paul.

> Is there a reason you don't see assuming a timezone of
> win32timezone.GetLocalTimeZone() as a reasonable option?

Not really - I think I was just looking at it from the POV of the win32
structures.  You make a good case for using the local time, but there may
still be some rough edges...

> It seems like
> the right thing to do to me. (If the user is using timzone-naive
> objects, they are probably naive about timezones, and hence likely to
> be assuming that the "local" timezone applies).

My proposal was to always *return* tz-aware datetime objects in a UTC
time-zone.  In some cases this will force such people to become tz-aware,
but such people are still likely to be surprised to see the times printed in
UTC - some may even conclude that a UTC naïve time is indeed required - eg:

>>> win32file.GetFileTime(handle)
<snip 3 times printed in UTC - eg, '2009-01-14 01:28:32+00:00'
# tz-naïve developer thinks "*grumble* - apparently need to use UTC"
>>> now = datetime.datetime.utcnow()

On the other hand, as I've mentioned to Jason, I'm reluctant to cache the
result value of GetLocalTimeZone() in sight of long-running processes
running during a transition - although Jason has recently made the
implementation more light-weight, there is still *some* registry work which
I'd like to avoid for each and every time object we return.  Caching UTC
appears to be reasonable though.

Maybe I'm just doing too much premature optimization?  Or maybe concerned
over nothing and always returning tz-aware UTC while assuming "local time"
for non-tzaware objects wouldn't cause confusion (or at least only
short-term confusion gaining knowledge they ultimately need anyway)?

A final option is worth throwing out even though I don't think I like it
much: return objects in either UTC or local time depending on how
performance critical it is likely to be.  eg, COM and ODBC would probably
want the fast UTC, while GetFileTime(), which operates on a single file,
probably isn't really that critical - but win32api.FindFiles probably *is*
(eg, listing a huge directory) - mqking things somewhat arbitrary in
practice.
 
Responding to Jason's other idea: I think it makes perfect sense for
win32timezone to expose now and utcnow functions.

Cheers,

Mark




More information about the python-win32 mailing list