django mysql 时间,Python / Django MySQL日期时间处理和时区

I've got a model called Vote with a field date :

date = models.DateTimeField(auto_now_add=True)

When I add an element, the date in MySQL is an UTC date but I live in UTC+2 timezone

I think I correctly set the timezone in settings.py :

TIME_ZONE = 'Europe/Paris'

Python use the right timezone :

>>> print datetime.datetime.now()

2013-07-03 09:05:04.474000

MySQL too :

> SELECT NOW( )

2013-07-03 09:00:48

I could set the date attribute manualy, it works but I would like to know why auto_now_add return a wrong date although python and mysql use the right timezone

Thank you

解决方案

It's a complex binding to explain. From Django 1.4,

When USE_TZ is False, this is the time zone in which Django will store

all datetimes. When USE_TZ is True, this is the default time zone that

Django will use to display datetimes in templates and to interpret

datetimes entered in forms.

this refers to TIME_ZONE. So what is your USE_TZ? If your USE_TZ is True then Django will store datetime in UTC and use TIME_ZONE to display in templates and interpret forms.

This is because, if you change your TIME_ZONE later when hosting your site in another territory, it's easy to convert any datetimes from UTC to any timezones given.

In Django 1.3 and earlier,

Note that this is the time zone to which Django will convert all

dates/times – not necessarily the timezone of the server. For example,

one server may serve multiple Django-powered sites, each with a

separate time-zone setting.

Normally, Django sets the os.environ['TZ'] variable to the time zone

you specify in the TIME_ZONE setting. Thus, all your views and models

will automatically operate in the correct time zone.

But doesn't tell you in what timezone the datetime will be stored in database. Need to experiment anyway(my guess is UTC).

print datetime.datetime.now() prints the datatime according to the timezone setup of your server machine unless you have opened the python console via manage.py shell.

Same goes for MySQL console. It shows the datetime in your machine timezone rather than what's stored in database if I'm right.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值