Comments (19)
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
)
from freezegun.
@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.)
from freezegun.
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.
from freezegun.
@shreevatsar solution does not work for me.
I might be doing something wrong, but definitely this is not very straightforward.
from freezegun.
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
from freezegun.
I got same problem with freezing time in Django tests =/
from freezegun.
Not sure if you know this, but freeze_time
already accepts a tz_offset
argument.
If your suggestion was just to make it cleaner so that we could pass in 'nice' timezone names, then I could get behind that.
from freezegun.
Yes, I've seen tz_offset
. The problem is that (1) it requires explicit knowledge about the offset (2) the offset changes depending on the datetime.
from freezegun.
Ah, right. I had forgotten about your second point. PR welcome.
from freezegun.
You don't need to put pytz
in the requirements, it can be optional (try: import; except ImportError: pytz = None
pattern) and then only used if timezone
is passed.
from freezegun.
AFAIK you can also pass a timezone in the string, right?
with freeze_time("2015-03-09 09:00:00 PST")
from freezegun.
Going to close this with support for @shreevatsar 's solution
from freezegun.
Happy to accept a PR for it, but don't want to leave the issue open forever.
from freezegun.
I am also not getting the described behaviour:
In [4]: dt = datetime(2018,1,1,tzinfo=pytz.timezone('America/Los_Angeles'))
In [6]: with freeze_time(dt):
...: print(datetime.now())
...:
2018-01-01 07:53:00
Ignoring the whacky time (this is caused by most timezones not being suitable for use as the tzinfo
parameter) this is not even an aware datetime as @shreevatsar said (maybe this is a regression?)
from freezegun.
@spulec for me @shreevatsar 's solution doesn't work as well
from freezegun.
This worked for me (I already had a helper function for tests) on Django + pytest + freezegun
from datetime import datetime
from django.utils.timezone import get_current_timezone
def to_datetime(str_date: str, time: bool = False) -> datetime:
str_format = "%Y-%m-%d"
if time:
str_format += "-%H:%M:%S"
return datetime.strptime(str_date, str_format).astimezone(get_current_timezone())
On the tests:
with freeze_time(to_datetime("2020-01-12")):
...
from freezegun.
Be ware when work with aware datetimes: #348
from freezegun.
Is there any technical reason why you're convert_to_timezone_naive()
before setting the time? Is this absolutely needed?
from freezegun.
@spumer @realmhamdy thanks for pointing to that issue - very helpful!
from freezegun.
Related Issues (20)
- `time_to_freeze.today()` returns wrong time and type if TZ is not 'UTC' in env vars HOT 2
- 'FakeDatetime' object cannot be interpreted as an integer
- Timezone America/Sao_Paulo triggers recursion errors in tests. HOT 3
- Maintenance plans HOT 3
- 1.3.0: `freezegun/__init__.py` is missing new version number HOT 1
- [Discussion] about freezing asyncio HOT 7
- ``PermissionError: [Errno 1] Operation not permitted`` appears when upgrading to ``1.3.0`` HOT 7
- Freezegun doesn't mock pointers to date functions HOT 1
- Tag for 1.2.2 is missing HOT 1
- Python 3.12: Deprecation warnings related to datetime.datetime.utcfromtimestamp HOT 2
- Time is not freezed when using `uvloop` event loop
- unsupported operand type(s) for +: 'FakeDatetime' and 'FakeDatetime'
- Datetime and Time packages do not have the same behavior when being frozen HOT 4
- timezone free datetime.datetime.fromtimestamp returns original datetime.datetime HOT 1
- Adding a return value to tick()
- Could have some problem with Django with TIME_ZONE setting
- Test regressions on Python 3.13.0b1 HOT 2
- `FakeDatetime`'s `timestamp()` is not consistent with `datetime().timestamp()` HOT 1
- consider overriding == on FakeDatetimeMeta HOT 2
- Freeze time doesn't work with FastAPI + pydantic V2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from freezegun.