【问题标题】:Get current time zone (Django)获取当前时区(Django)
【发布时间】:2020-04-28 14:50:58
【问题描述】:

我目前在我的设置中设置了TIME_ZONE = 'UTC'

在我的 DebitCard 模型 expiration_date 字段中,我将日期存储为 unixtime。例如 01/10/2020 @11:25pm (UTC) 是 1578698708

问题是:

假设expiration_date2010 年 1 月 15 日 00:00 或 (1263513600)。

我想在当前时间大于expiration_date时阻止用户进行交易。

但是,如果用户在洛杉矶(UTC 前 8 小时),current_time 将关闭 8 小时。

问题:

无论用户身在何处(不仅仅是在洛杉矶),我如何获取他们的当前时间?因为我想抓住这个时间和他们的借记卡比较expiration_date

【问题讨论】:

  • 据我了解,当您的服务器收到请求时,会有一个时间戳,只需将其与 expire_date 进行比较即可,您不一定需要知道用户的时区。

标签: python django time timezone pytz


【解决方案1】:

试试这个。

from django.contrib.gis.utils import GeoIP
from .utils import GeoTimeZoneReader


  g = GeoIP()  # get user ip
  g.city(request.META['REMOTE_ADDR'])
  g.city('74.125.79.147') # get city 
to get timezone 

  data = GeoIP().city('74.125.79.147')

  # Get Time Zone
  db = GeoTimeZoneReader()
  db.get_timezone(data['country_code'], data['region'])

【讨论】:

    【解决方案2】:

    如果您想确保您的代码使用 UTC 时间进行比较,请使用 datetime.datetime.utcnow()

    例如,尝试在 python 或 manage.py shell 中运行以下命令:

    import datetime
    print(datetime.datetime.utcnow())
    

    您可以将其输出与简单的datetime.datetime.now() 进行比较。如果您使用的计算机不是 UTC,now() 和 utcnow() 会有所不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-09
      • 2016-09-27
      • 1970-01-01
      • 2019-12-15
      • 2022-01-08
      • 2017-03-13
      • 2016-09-03
      • 1970-01-01
      相关资源
      最近更新 更多