mysql - 如何将Mysql日期时间格式 "2015-10-10 10:30:59.108000"转换为用户可读格式,如 "Oct. 10, 2015, 2:31 p.m"

标签 mysql django python-2.7 django-models

6、python 2.7,带MYSQL数据库。

详细内容如下

settings.py

#Mysql database connection
DATABASES = {
    'default': {
        'ENGINE':'django.db.backends.mysql',
        'NAME': 'monitoringtool',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

模型.py

class MonitoringDetail(models.Model):
    host_id = models.ForeignKey('HostDetail')
    transac_date = models.DateTimeField(auto_now_add=True, blank=True)    
    def __unicode__(self): 
        return '%s %s %s'% (self.id, self.host_id, self.transac_date)

views.py

date_objects = MonitoringDetail.objects.all()
for date_object in date_objects:
            transac_date = date_object.transac_date
            print transac_date

在上面的 View 中,当我打印 transac_date 时,它​​会以这种格式显示日期:2015-10-10 08:38:25.299000+00:00 但实际上我想以这种格式日期:Oct。 2015 年 10 月 10 日下午 2:31

请帮助我,我不确定我错过了什么?

最佳答案

Django DateTimeField 已标准化为 python 日期时间,您可以使用库提供的方法来格式化日期。您看到的日期是默认日期。这是文档的链接: https://docs.python.org/2/library/datetime.html#datetime.date.strftime

对于您的情况,您需要: print transac_date.strftime('%b.%d, %Y, %I:%m %p')

关于mysql - 如何将Mysql日期时间格式 "2015-10-10 10:30:59.108000"转换为用户可读格式,如 "Oct. 10, 2015, 2:31 p.m",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33053864/

相关文章:

php - 使用php循环遍历mysql表,为什么elseif语句不起作用?

mysql - 使用 count() 分组

python - 使用 Python 的 Popen 类从 Django 调用 Matlab 脚本

python - 在 Django 中使用 OneToOneField

python - 如何在Python中精确匹配一个单词然后进行替换?

mysql - 在大于 TIME 范围的 MySQL 中存储持续时间的最佳方法是什么?

mysql - 使用内连接合并两个表时如何将列设置为主键?(两个连接表中没有主键)

python - django,基于位置的搜索

django - 由于 gdal 库,heroku push 被拒绝

python - Linux允许python使用多少个网口?