【问题标题】:Change time format in Django Views在 Django 视图中更改时间格式
【发布时间】:2013-04-22 18:14:44
【问题描述】:

importdatetime

在我的 django 视图中 以节省 数据库 中的时间

now = datetime.datetime.now()

当我保存它在数据库中的值时,它返回类似于

2013-04-28 22:54:30.223113

如何删除

223113 来自 2013-04-28 22:54:30.223113

请建议我该怎么做...

【问题讨论】:

  • 你保存在什么样的字段中?
  • 它是一个文本字段,但由于某种原因我无法将其更改为日期时间字段

标签: python django date format


【解决方案1】:

理想情况下,您应该在数据库中使用日期时间字段。但是如果有一个约束 您将日期存储为字符串使用它来格式化它:

>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") 
'2013-04-29 12:17:55'

【讨论】:

    【解决方案2】:

    你可以这样做:

    import datetime
    n = datetime.datetime.now() # you'll get the datetime you already have
    n.strftime("%d/%m/%y %H:%M:%S") 
    # Now you have the string of the datatime with the format 
    # day/month/year hour:minute:seconde
    

    看看这个部分:http://docs.python.org/2/library/datetime.html#datetime.datetime.strftime

    玩得开心!

    【讨论】:

      【解决方案3】:

      设置microsecond=0。但我在文档中找不到这个功能。'

      >>> now = datetime.datetime.now().replace(microsecond=0)
      >>> print now
      2013-04-29 12:47:28
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多