为什么datetime.now()在django服务器中执行时显示无效结果?

时间:2010-05-19 14:20:38

标签: python django datetime

案例1

>>> datetime.__file__
'/usr/lib/python2.6/lib-dynload/datetime.so'
>>> print datetime.datetime.now()
2010-05-19 19:45:40.202634

案例2

from django.db import models
import datetime
print datetime.__file__
print "--------------------------", datetime.datetime.now()

----------- --------结果

Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Validating models...
/usr/lib/python2.6/lib-dynload/datetime.so
-------------------------- 2010-05-19 09:16:43.987508
0 errors found

1 个答案:

答案 0 :(得分:3)

正如马克指出的那样,日本看起来像时区:

>>> from dateutil import tz
>>> from datetime import datetime
>>> utc_time = datetime(2010, 5, 19, 9, 16, 43, tzinfo=tz.tzutc())
>>> jst_time = utc_time.astimezone(tz.gettz('Japan'))
>>> print utc_time
2010-05-19 09:16:43+00:00
>>> print jst_time
2010-05-19 18:16:43+09:00

标准datetime模块仅处理天真时间,您可以使用dateutil(尤其是dateutil.tz.tzlocal()构造函数)添加时区支持。