ValueError: pytz.timezone('UTC').fromutc(datetime.utcnow())

Bug #879480 reported by Alain Spineux
6
This bug affects 1 person
Affects Status Importance Assigned to Milestone
pytz
Fix Released
Medium
Stuart Bishop

Bug Description

>>> pytz.timezone('UTC').fromutc(datetime.utcnow())

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: fromutc: dt.tzinfo is not self
>>> pytz.timezone('Europe/Brussels').fromutc(datetime.utcnow())

datetime.datetime(2011, 10, 19, 9, 55, 47, 787937, tzinfo=<DstTzInfo
'Europe/Brussels' CEST+2:00:00 DST>)

Why does UTC fail ?
Bug or feature ?

Alain

Related branches

Stuart Bishop (stub)
Changed in pytz:
status: New → Confirmed
importance: Undecided → Medium
Revision history for this message
Stuart Bishop (stub) wrote :

This exception is coming from Python - the default tzinfo.fromutc is designed to be called from datetime.astimezone()

Revision history for this message
Stuart Bishop (stub) wrote :

There doesn't seem any harm adding support for naive datetime instances and making behavior consistent.

Changed in pytz:
status: Confirmed → Fix Committed
assignee: nobody → Stuart Bishop (stub)
Revision history for this message
Alain Spineux (alain-spineux) wrote :

I get naive datetime from SqlAlchemy in UTC and want to display it in the user 's local timezone, I used this

pytz.timezone(USER_LOCAL_TIMEZONE).fromutc(DATETIME_FROM_SQLALCHEMY)

If i'm wrong please tell me !

datetime.astimezone() works, but with some more code because it doesn't expect a naive datetime

>>> datetime.datetime.utcnow().replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Europe/Brussels'))
datetime.datetime(2011, 11, 4, 10, 36, 51, 416512, tzinfo=<DstTzInfo 'Europe/Brussels' CET+1:00:00 STD>)
>>> datetime.datetime.utcnow().replace(tzinfo=pytz.utc).astimezone(pytz.timezone('utc'))
datetime.datetime(2011, 11, 4, 9, 37, 5, 320588, tzinfo=<UTC>)

Thanks

Stuart Bishop (stub)
Changed in pytz:
status: Fix Committed → Fix Released
Revision history for this message
Stuart Bishop (stub) wrote :

Yes, I think the 'correct' version is complex but is what is supported by the base Python tzinfo implementation.

I have extended this in pytz-2011n so you should now be able to use your preferred, less cumbersome syntax with code expecting pytz tzinfo instances.

This pytz syntax also works if you need to use an older version:

utc = pytz.utc
brussels = pytz.timezone('Europe/Brussels')
utc.localize(datetime.utcnow()).astimezone(brussels)

To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.