【问题标题】:Django - UTC to Local Time Conversion failsDjango - UTC 到本地时间转换失败
【发布时间】:2020-08-18 13:18:20
【问题描述】:

我想将我的 UTC 时间转换为我的本地时间

我的设置.py

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

我的模型.py

class UnauthorizedAccess(models.Model):
    UnauthorizedAccessId = models.AutoField(primary_key=True, db_column='UnauthorizedAccessId')
    Camera = models.ForeignKey(Camera, on_delete=models.CASCADE, db_column='CameraId')
    AccessTime = models.DateTimeField()
    Description = models.CharField(max_length=250)

    class Meta:
        db_table = "UnauthorizedAccess"

views.py

from datetime import date, datetime
from django.utils import timezone
from tzlocal import get_localzone
import pytz

@api_view(['POST'])
@permission_classes([])
def push_notification(request):
        cam_id = request.data.get("CameraId").strip()
        camera_ob = Camera.objects.get(CameraId=cam_id)
        unauthorized_entry = UnauthorizedAccess(
            Camera=camera_ob,
            AccessTime=timezone.now(),
            Description=unauthorized_access,
        )
        unauthorized_entry.save()
        return Response({msg:  validation["FDP25"]}, status=status.HTTP_200_OK)
    except Exception as ex:
        logging.getLogger("error_logger").exception(repr(ex))
        return Response({msg: validation["FDP23"]}, status=status.HTTP_400_BAD_REQUEST)

在保存时我尝试了 AccessTime=datetime.now(tz=timezone.utc) 和 AccessTime=datetime.now() 现在我正在使用 timezone.now()

我的数据库保存了数据

我尝试检索我的数据

我的意见.py 从日期时间导入日期,日期时间 从 django.utils 导入时区 从 tzlocal 导入 get_localzone 导入pytz

@api_view(['GET'])
@permission_classes([])
def notification(request):
    try:
        unauthorizedaccess_details = list()
        tz = get_localzone()
        notification_ob = UnauthorizedAccess.objects.all().order_by('-AccessTime')[:50]
        for ob in notification_ob:
            dev = Device.objects.get(Camera=ob.Camera)

            tz = get_localzone()
            localtz = ob.AccessTime.replace(tzinfo=pytz.utc).astimezone(tz)
            date_time = localtz.strftime("%d/%m/%Y %I:%M:%S %p")

            tz1 = ob.AccessTime.replace(tzinfo=pytz.UTC)
            localtz1 = tz1.astimezone(timezone.get_current_timezone())
            date_time1 = localtz1.strftime("%d/%m/%Y %I:%M:%S %p")

            unauthorizedaccess_info = {
                'id': ob.UnauthorizedAccessId,
                'DeviceName': dev.DeviceName,
                'Date': date_time,
                'Date1': date_time1,
                'Date2': ob.AccessTime,
                'Date3':  ob.AccessTime.strftime("%d/%m/%Y %I:%M:%S %p"),
                'Access': ob.Description,
                'Type': '1'
            }
            unauthorizedaccess_details.append(unauthorizedaccess_info)
            return JsonResponse(unauthorizedaccess_details, safe=False,  status=status.HTTP_200_OK)
    except Exception as ex:
        logging.getLogger("error_logger").exception(repr(ex))
        return Response({msg: validation["FDP23"]}, status=status.HTTP_400_BAD_REQUEST) 

我尝试了这些方法来获取正确的时间

当我使用我的 localhost 作为 url 运行它时,我得到了这个答案(我只显示 1 个集合数据作为示例)

{
        "id": 124,
        "DeviceName": "FDP01",
        "Date": "18/08/2020 06:14:43 PM",
        "Date1": "18/08/2020 12:44:43 PM",
        "Date2": "2020-08-18T12:44:43.127Z",
        "Date3": "18/08/2020 12:44:43 PM",
        "Access": "Unauthorized entry",
        "Type": "1"
    }

那么使用我的服务器 url 获取的相同数据是

{
        "id": 125,
        "DeviceName": "FDP01",
        "Date": "18/08/2020 12:49:05 PM",
        "Date1": "18/08/2020 12:49:05 PM",
        "Date2": "2020-08-18T12:49:05.675Z",
        "Date3": "18/08/2020 12:49:05 PM",
        "Access": "Unauthorized entry",
        "Type": "1"
    }

我希望服务器的答案是“日期”:“18/08/2020 06:14:43 PM”,这些格式(日期1和日期2是我尝试过的代码示例)

使用服务器 url 日期不会转换为我的本地时区

  1. 我怎样才能得到正确的日期?
  2. 我犯了什么错误?

【问题讨论】:

    标签: python django django-models utc django-timezone


    【解决方案1】:

    有几种方法可以实现这一点。

    Django 设置'TIME_ZONE'

    根据docs,您可以将此设置设置为您想要的任何有效时区。 Django 负责从您在此处指定的时区转换数据库中的时间戳。 因为您将 TIME_ZONE 设置为“UTC”,所以您没有使用这个方便的功能。

    手动转换 DateTime 对象

    您可以自行从一个时区转换到另一个时区。

    from django.utils import timezone
    local_tz = timezone.get_current_timezone() # Asking django about the current timezone
    # Django gets this information from the incoming request
    my_datetime_local = my_datetime.astimezone(local_tz) # Use this method to change the timezone of already aware datetime objects
    

    我不是 100% 确定,但我认为来自 pytz 的方法 get_localzone() 可以检索您机器的本地时区。我认为这不是你想要的。 最好使用 djangos helper timezone 对时区感知日期时间对象进行所有修改。

    【讨论】:

      猜你喜欢
      • 2021-02-04
      • 2020-01-11
      • 1970-01-01
      • 2018-07-27
      • 1970-01-01
      • 2017-07-22
      • 2014-07-18
      • 2010-09-15
      • 2016-07-29
      相关资源
      最近更新 更多