如何在Faker中生成感知时间对象?

发布于 2025-01-13 09:12:46 字数 958 浏览 2 评论 0原文

我有以下(简化的)模型和工厂:

models.py

class Event():
    duration = FloatField()
    start_time = TimeField()
    finish_time = DateTimeField()

    def save(self, *args, **kwargs):
        self.finish_time = self.start_time + timedelta(hours=self.duration)

event_factory.py

from factory import Faker

class EventFactory:
    date = Faker(
        "date_time_this_month",
        before_now=False,
        after_now=True,
        tzinfo=timezone.get_current_timezone(),
        )
    start_time = Faker("time_object")
    duration = Faker("random_int")

但是,我的 save 方法引发 警告:DateTimeField Event.finish_time 收到了一个幼稚的日期时间 (2022-03-28 12 :43:38) 当时区支持处于活动状态时。

由于 tzinfo 参数,date 是已知的,但是start_time 很幼稚(我检查了 django 的 timezone.is_aware()),因为 Faker 中的时间提供程序似乎不允许任何时区参数。

关于在 Factory-boy/Faker 中获取假感知时间对象有什么建议吗?

I have the following (simplified) model and factory:

models.py

class Event():
    duration = FloatField()
    start_time = TimeField()
    finish_time = DateTimeField()

    def save(self, *args, **kwargs):
        self.finish_time = self.start_time + timedelta(hours=self.duration)

event_factory.py

from factory import Faker

class EventFactory:
    date = Faker(
        "date_time_this_month",
        before_now=False,
        after_now=True,
        tzinfo=timezone.get_current_timezone(),
        )
    start_time = Faker("time_object")
    duration = Faker("random_int")

However, my save method raises Warning: DateTimeField Event.finish_time received a naive datetime (2022-03-28 12:43:38) while time zone support is active.

date is aware due to tzinfo argument, but start_time is naive (I checked with django's timezone.is_aware()), because time providers in Faker do not seem to allow any timezone parameters.

Any suggestion in getting a fake aware time object in factory-boy/Faker?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷︶言冷语的世界 2025-01-20 09:12:46

正如 @Bridge 所说,大多数 FactoryBoy 的内置模糊器已被弃用,取而代之的是 Faker 的同类产品。请参阅https://factoryboy.readthedocs.io/en/stable/fuzzy.html

要在 Faker 中生成感知时间对象,您可以使用 tzinfo 参数:

from datetime import UTC

created_at = factory.Faker("date_time", tzinfo=UTC)

As @Bridge stated, most FactoryBoy's built-in fuzzers are deprecated in favor of their Faker equivalents. See https://factoryboy.readthedocs.io/en/stable/fuzzy.html

To generate aware time object in Faker you can use the tzinfo parameter:

from datetime import UTC

created_at = factory.Faker("date_time", tzinfo=UTC)
梦旅人picnic 2025-01-20 09:12:46

尝试使用 FuzzyDateTime 对象,它们返回时区感知对象: https:/ /factoryboy.readthedocs.io/en/stable/fuzzy.html?highlight=timezone

Try to use FuzzyDateTime objects, they return a timezone aware object: https://factoryboy.readthedocs.io/en/stable/fuzzy.html?highlight=timezone

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文