1. python datetime from datetime import datetime datetime.now() datetime.utcnow() from datetime import datetime,timezone,timedelta dt = datetime.utcnow() print(dt) dt = dt.replace(tzinfo=timezone.utc) print(dt) tzutc_8 = timezone(timedelta(hours=8)) local_dt = dt.astimezone(tzutc_8) print(local_dt) 2.django timezone from django.utils import timezone timezone.now() from datetime import datetime datetime.now()
import pytz
#pytz.country_timezones('cn')[0]
#u'Asia/Shanghai'
tz = pytz.timezone(pytz.country_timezones('cn')[0])
datetime.now(tz)
#datetime.datetime(2016, 10, 18, 14, 40, 24, 950672, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)
datetime.now(tz=None)
datetime.datetime(2016, 10, 18, 6, 40, 43, 725325)
参考资料: https://segmentfault.com/q/1010000000148274 http://ar.newsmth.net/thread-f9b7985b2132c6.html http://www.zhihu.com/question/27934615 http://stackoverflow.com/questions/18622007/runtimewarning-datetimefield-received-a-naive-datetime
http://www.cnblogs.com/lhj588/archive/2012/04/23/2466653.html
http://www.360doc.com/content/14/0626/18/8504707_390057412.shtml
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 datetime from django.utils import timezone from django.utils.timezone import utc time.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
http://tool.chinaz.com/tools/native_ascii.aspx
http://tool.lu/timestamp
https://my.oschina.net/u/1032854/blog/198179