Django: time zone issue

后端 未结 4 1648
一整个雨季
一整个雨季 2021-02-01 09:44

NOTE: I deleted the question as it existed previously and providing only the relevant info here.

Our database server (RH) has TIME_ZONE = \"Europe/London\" specified. An

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-01 10:30

    First off, I would want to store my data as UTC cause its a good starting point.

    So let me ask this, Why do you need the time in EST, is this for the end-user, or do you need to do logic on the server and need it in EST?

    If its for the enduser, an easy fix is to let the users browser handle converting to the correct time. On the server convert the datetime object to a timestamp:

    timestamp = time.mktime(datetime_obj.timetuple()) * 1000
    

    And then on the web page instantiate a Date object:

    var date_obj = new Date({{ timestamp }});
    var datetime_string = date_obj.toString();
    // the datetime_string will be in the users local timezone
    

    Now, on the other hand, if you want to have the time in the correct zone on the server so you can perform logic on it. I recommend using the help of python-dateutil. It will allow you to easily swap to a different timezone:

    from datetime import datetime
    from dateutil import zoneinfo
    
    from_zone = zoneinfo.gettz('UTC')
    to_zone = zoneinfo.gettz('America/New_York')
    
    utc = created # your datetime object from the db
    
    
    # Tell the datetime object that it's in UTC time zone since 
    # datetime objects are 'naive' by default
    utc = utc.replace(tzinfo=from_zone)
    
    # Convert time zone
    eastern_time = utc.aztimezone(to_zone)
    

    Now if you really wanna store the datetime in EST, you need change the time on the DB server (like Ajay Yadav and gorus said). I don't know why you want to store them as EST, but then again I don't know what your application is.

提交回复
热议问题