Home > Back-end >  Why is my date in python wrong after formating using timedelta?
Why is my date in python wrong after formating using timedelta?

Time:10-20

I am using Django and have a problem with a date that I need to calculate. The Variable data > test should be 17:00 and not 15:00. Why does this happen as soon as I format the date?

My timezone is Europe/Berlin. Changing the timezone has to effect to the time printing in test. It is always -2h

def date(req):
    now = timezone.now()
    model = MyModel.objects.filter(date__gt=now).first()
    next = model.date
    future = timezone.timedelta(hours=float(model.future)) #model.future = 1.5
    open = next-future
    date = next.strftime('%Y/%m/%d')
    data = {
        'next': next,
        'date': date,
        'time': open.astimezone(timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f'),
        'test': open.strftime('%Y/%m/%d %H:%M:%S%z')
    }

What I get:

next: 20. November 2021 18:30
date: 2021/11/20
time: 2021-11-20 15:15:00.000000
test: 2021/11/20 15:00:00 0000

CodePudding user response:

https://docs.djangoproject.com/en/3.2/topics/i18n/timezones/#naive-and-aware-datetime-objects

You should use:

from django.utils import timezone
now = timezone.now()

Datetime isn't time-zone aware.

CodePudding user response:

You cut the timezone info (the offset 02:00) with .strftime(). You need to include it with %z.

In case you want to convert it to a time string with the offset already added.

open.astimezone(timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f')

  • Related