首页 > 代码库 > 【Python】Django 时间字段 最佳实践

【Python】Django 时间字段 最佳实践

Model定义:

class Test(models.Model):    id = models.AutoField(primary_key=True)    name = models.CharField(max_length=128, unique=True, db_index=True)    #create_time = models.DateTimeField(auto_now_add=True, db_index=True)    #update_time = models.DateTimeField(auto_now=True, db_index=True)    create_time = models.DateTimeField(default=timezone.now, db_index=True)    update_time = models.DateTimeField(default=timezone.now)    description = models.TextField(null=False, blank=True)

datetime转化为时间戳:

from datetime import datetimefrom django.utils import timezonefrom django.utils.timezone import utctime.mktime(timezone.now().timetuple())

时间戳转化为datetime:

datetime.utcfromtimestamp(1476321626.0).replace(tzinfo=utc)

 

 

参考资料:

http://stackoverflow.com/questions/13225890/django-default-timezone-now-saves-records-using-old-time

时间戳与datetime相互转换:http://blog.sina.com.cn/s/blog_771875550101jfw2.html

 

【Python】Django 时间字段 最佳实践