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

Bri*_*dge 5 python django class faker factory-boy

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

模型.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)
Run Code Online (Sandbox Code Playgroud)

事件工厂.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")
Run Code Online (Sandbox Code Playgroud)

但是,我的save方法提出了Warning: DateTimeField Event.finish_time received a naive datetime (2022-03-28 12:43:38) while time zone support is active.

date由于参数而知道tzinfo,但start_time很天真(我用 django 检查过timezone.is_aware()),因为 Faker 中的时间提供程序似乎不允许任何时区参数。

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

hen*_*der 1

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

  • 谢谢。我最终只是使用“datetime”模块对日期和时间进行硬编码。我将尝试 FuzzyDateTime,但是文档中的注释让我感到困惑:“现在 FactoryBoy 包含了factory.Faker 类,大多数内置模糊器都已被弃用,取而代之的是 Faker 等效项。” (2认同)