python - 为什么系统的时区是东八,但是存数据还是存的标准时?
黄舟
黄舟 2017-04-17 15:01:52
0
5
224

通过DjangoAPI来存:

pythonfrom django.db import models class Chirp(models.Model): content = models.TextField() pub_time = models.DateTimeField(auto_now=True) def __str__(self): return self.content[:20]+ '...'

template中:

html{% for chirp in chirp_page %} 

{{ chirp.pub_time.hour }}:{{ chirp.pub_time.minute }}, {{ chirp.pub_time.day }}-{{ chirp.pub_time.month }}-{{ chirp.pub_time.year }}  说:{{ chirp.pub_time }}

{{ chirp.content }}

{% endfor %}

显示效果示例:

因为我在Django项目里面也设置了时区,所以后面那个时间能正确显示(是这个原因吧。。。),但是通过属性来取的时候就跟数据库里一样了,看下面的图。

数据库中(注意time_zone):

系统的时区:

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all (5)
Peter_Zhu

Because you only have two choices:

  1. Or save all times with time zone
  2. Or save all times in the same time zone

The first item will cause a lot of unnecessary storage and trouble (cannot be directly compared and calculated), so everyone uses the second item. And what time zone to use? By definition, UTC is the most reliable. Other time zones have names, applicable areas, and offsets from UTC that change for various reasons.

    刘奇

    The data stored in the database is UTC time. If the time zone is set, it will be converted according to the corresponding rules when displayed

      Peter_Zhu

      Because this is the best thing to do.
      The benefits of doing this are:

      1. What if you want a feature that can display different times based on the customer’s geographical location?
      2. By default, all times are UTC time, so no matter what system it is connected to, there is no need to add another time zone information. Everyone knows that this is UTC, and then converted according to needs.
        伊谢尔伦

        "Time zone" is completely a display concept, a "UI" concept;
        The storage of time should not have anything to do with "time zone";
        It is recommended to store the milliseconds directly

          Peter_Zhu

          Consider this problem. Your users come from all over the world. If your time is stored in a certain time zone, and users in different time zones visit your page, how do you convert it to the user’s local time? to show?
          So what is stored on the server is UTC time. When the user accesses the page, the browser converts UTC time to local time. There is an extension like moment in Flask that does this job specifically. I haven't looked at your code carefully, but I believe that the principles are the same for both python web frameworks.

            Latest Downloads
            More>
            Web Effects
            Website Source Code
            Website Materials
            Front End Template
            About us Disclaimer Sitemap
            php.cn:Public welfare online PHP training,Help PHP learners grow quickly!