zoukankan      html  css  js  c++  java
  • 【Python】Django 时间字段 最佳实践

    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

  • 相关阅读:
    sql server该账户当前被锁定,所以用户'sa'登录失败。系统管理员无法将该账户解锁。(Microsoft SQL Server,错误:18486)
    windows server常用操作
    sql server2005直接会话运行成功,但在作业执行报错
    sql server xp_readerrorlog引起的CPU爆满100%
    sql server错误日志
    (13)python网络编程,python Socket
    tcp/ip
    (12)python异常处理,python中的 try except
    典型分布式系统分析:Dynamo
    c++ set与unordered set的区别
  • 原文地址:https://www.cnblogs.com/junneyang/p/5955177.html
Copyright © 2011-2022 走看看