freezegun: `freeze_time` could accept a timezone argument

What do you think of having freeze_time accept a timezone argument:

@freeze_time('2015-03-09 09:00:00', timezone='US/Pacific')

That would require adding pytz to the requirements, which should be fine since most Python projects have it.

Thoughts? I might develop it.

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 2
  • Comments: 19 (7 by maintainers)

Most upvoted comments

Just FYI: one can already pass freeze_time a timezone-aware datetime object:

d = datetime(2015, 8, 18, 8, 51, 50, tzinfo=pytz.timezone('America/Los_Angeles'))
with freeze_time(d):
    print datetime.now()

(prints 2015-08-18 08:51:50-08:00)

@spulec That’s a shame. While it works, it’s a bit clumsy for an extremely common use case. (I, at least, have zero Python projects that can afford to ignore time zones.)

@shreevatsar solution does not work for me.

I might be doing something wrong, but definitely this is not very straightforward.

Screenshot from 2019-04-01 10-59-04

Regarding my previous comment, it turns out that dateutil’s parser returns an aware datetime IFF the timezone in the string matches the default timezone of the host. In all other cases, dateutil’s parser ignores the given timezone and returns a naive (and unadjusted) datetime.

>>> parse("12:00 EST")
datetime.datetime(2016, 1, 4, 12, 0, tzinfo=tzlocal())
>>> parse("12:00 CST")
datetime.datetime(2016, 1, 4, 12, 0)
>>> parse("12:00 MST")
datetime.datetime(2016, 1, 4, 12, 0)

Definitely fails the principle of least surprise for me, but there you have it.

i can confirm problem mentioned by @spumer @fish-face and @jose-lpa
my workaround:

from datetime import datetime

import arrow
from freezegun import freeze_time

d = datetime(2015, 8, 18, 8, 51, 50, tzinfo=arrow.now("America/Los_Angeles").tzinfo)
with freeze_time(d):
    print datetime.now()

2015-08-18 15:51:50

I got same problem with freezing time in Django tests =/