【问题标题】:how to create datetime object for a specific time in a timezone in django如何在 django 的时区中为特定时间创建日期时间对象
【发布时间】:2014-10-28 14:00:47
【问题描述】:

我有一个时间,我希望用户在该时间到达他们各自的时区时得到提醒。它存储为时间字段:

reminder = models.TimeField(blank=True, null=True)

我有一个与每个用户关联的时区。它看起来像:

customer1_timezone = customer1.time_zone #la timezone
customer2_timezone = customer2.time_zone #ny timezone

假设 customer1 和 customer2 都将提醒设置为早上 7 点。

我如何为每个用户指示相对于他们的时区的早上 7 点?

【问题讨论】:

    标签: python django datetime timezone pytz


    【解决方案1】:

    我用这样的东西

    def user_time(time_value, customer):
        tz = pytz.timezone(customer.time_zone)
        c_tz = pytz.timezone(settings.TIME_ZONE)
        d_tz = c_tz.normalize(c_tz.localize(time_value))
        return tz.normalize(d_tz.astimezone(tz))
    

    这将为客户争取到时间,然后您只需要检查它是早上 7 点。你甚至可以使用 strftime() 。 user_time(datetime.now(), customer).strftime("%H") == "07"

    【讨论】:

    • 什么是“价值”?我使用上面编辑的时间域。如何将我的时间字段转换为您的值字段?
    • Opps,'value' 应该是 'time_value'
    • @Atma:要从日期时间对象中获取一个小时(user_time() 返回它们),请使用 .hour 属性。
    • @Atma: 如果time_value 来自TimeField,那么你应该在传递给c_tz.localize() 之前将它与日期结合起来@:time_value = datetime.combine(datetime.now(c_tz).date(), time_value)。注意:settings.TIME_ZONE 中的早上 7 点可能对应于 customer.time_zone 中的不同时间。
    猜你喜欢
    • 2020-04-28
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 2011-10-27
    • 2021-09-18
    相关资源
    最近更新 更多