0

If I run this in VS Code, it gives me the correct local time:

from time import strftime
time = strftime("%H:%M %p")
print(time)

But if I use the same code in a Django project, my website displays a time which is 8 hours behind local time.

from time import strftime,localtime

def time_display(request):
    context = {
        "date":strftime("%b %d, %Y",localtime()),   #DOESN'T DISPLAY LOCAL TIME
        "time1": strftime("%H:%M %p",localtime()),  #DOESN'T DISPLAY LOCAL TIME
        "time3": strftime("%H:%M %p"),              #DOESN'T DISPLAY LOCAL TIME
    }
    return render(request,'time_display.html',context)

How do I fix it to display correct local time where the webpage is being viewed?

  • 1
    `localtime` would return local time of the server. You should get the loıcation/timezone of the browser and create a time object with timezone: https://stackoverflow.com/questions/7065164/how-to-make-a-timezone-aware-datetime-object-in-python – MSH Oct 11 '21 at 00:33

1 Answers1

0

Not an expert but you can change setting.py file like:

TIME_ZONE = 'Europe/London'

note: change Europe/London to your time zone.

You can find a list of timezone names here: http://en.wikipedia.org/wiki/List_of_tz_database_time_zones

sunil ghimire
  • 505
  • 4
  • 14