2

I'm trying to specify a set of timezone aware times in python, using datetime.time objects. However, this does not seem to be supported very well by the pytz library: using US/Pacific returns an odd timezone which is 53 minutes off UTC

>>> datetime.time(10, 52, tzinfo=pytz.timezone("US/Pacific"))
datetime.time(10, 52, tzinfo=<DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD>)

The supported way to do this, seems to be to use datetime.localize, for datetime.datetime objects, but this isn't supported for datetime.time objects

>>> pytz.timezone("US/Pacific").localize(datetime.datetime(2011, 6, 27, 2, 0, 0))
datetime.datetime(2011, 6, 27, 2, 0, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)
>>> pytz.timezone("US/Pacific").localize(datetime.time(10, 45))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/bar/.virtualenvs/foo/lib/python2.7/site-packages/pytz/tzinfo.py", line 309, in localize
    loc_dt = dt + delta
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'

1 Answers1

2

The problem is that the timezone is meaningless on the time without an associated date; say you have a date in US/Pacific timezone, which is not a constant offset; the actual adjustment depends on the exact date that time is supposed to occur.

As you noticed, if you use the US/Pacific as is, without localize, for a datetime, the tzinfo object by default refers to the historical timezone that was not offset with current UTC even by full hours, but some fractions; that is because the tzinfo instances do not know the datetime they are adjusting; the same problem would appear with time.

The best course of action would be to not use timezones for time; when timezone calculations are needed, you can add merge it with a localized datetime object.

  • Well, it is not. Python does support `tzinfo` for `time` objects, also there is `timetz()` for `datetime` objects, so you can have proper offset-aware `time` objects. It seems to me that just pytz does not support `tzinfo` for `time` objects properly. – Dmitry Mugtasimov Sep 12 '19 at 10:19
  • Works: `print(time(hour=14, minute=0, tzinfo=timezone(timedelta(hours=-4))) < datetime.fromisoformat('2019-09-11T10:00:00-04:00').timetz())` Does not work: `print(time(hour=14, minute=0, tzinfo=pytz.timezone('US/Eastern')) < datetime.fromisoformat('2019-09-11T10:00:00-04:00').timetz())` – Dmitry Mugtasimov Sep 12 '19 at 10:28
  • @DmitryMugtasimov obviously you've ignored everything I told in my answer. – Antti Haapala -- Слава Україні Sep 12 '19 at 10:32
  • This is how one can convert to timezone usable with time objects: `from datetime import timezone, timedelta, datetime; timezone(timedelta(seconds=datetime.now(tzinfo).utcoffset().total_seconds()))` – Dmitry Mugtasimov Sep 12 '19 at 10:44