Python日期时间.strptime仅适用于开发环境

2024-06-26 13:54:38 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码:

for i in report:
    reports.append({
        'total':i['vends__sum'],
        'date':datetime.strptime(i['month'], "%Y-%m-%d %H:%M:%S")
    })

这在我的OSX开发环境(virtualenv-django 1.5)上有效

但在我的生产服务器(ubuntu 12.04 virtualenv django 1.5)上,它无法处理以下错误:

^{pr2}$

第41行是

'date':datetime.strptime(i['month'], "%Y-%m-%d %H:%M:%S")

我不明白为什么在一种环境下工作而另一种环境不起作用?这里谁错了,开发人员还是生产人员?在

Prod : Python 2.7.3
Dev: Python 2.7.1

更多:

报告是这样制作的:

truncate_date = connection.ops.date_trunc_sql('month','timestamp')
qs = objects.extra({'month':truncate_date})
report = qs.values('month').annotate(Sum('vends')).order_by('month')

Tags: django代码inreportfordatetimedate环境
2条回答

strptime会生成一个datetime对象,在调试环境中该对象是可打印的,对于生产,您需要将其更改为:

datetime.strptime(i['month'], "%Y-%m-%d %H:%M:%S").format('how you would like to display it')

但由于strptime通常用于将日期/时间从字符串转换为datetime对象,所以我不确定为什么不直接使用字符串。即 “日期”:我['month']

在您的生产环境中,i['month']已经是一个datetime.datetime对象:

>>> import datetime
>>> example = u'2013-06-01 00:00:00'
>>> example = datetime.datetime.strptime(example, "%Y-%m-%d %H:%M:%S")
>>> example = datetime.datetime.strptime(example, "%Y-%m-%d %H:%M:%S")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be string, not datetime.datetime

因此,为了找出生产环境和开发环境之间的区别,您必须跟踪产生report的内容,并找出为什么一个环境生成字符串,而另一个环境生成datetime.datetime对象。在

如果您在服务器后端使用日期时间操作,请考虑到有些SQL服务器支持本机日期时间算法,但SQLite(通常用于开发的数据库)不支持。PostgreSQL将生成datetime对象,SQLite生成字符串。在

您要么希望根据数据库设置切换处理日期的方式,要么检测是否已有一个datetime对象并跳过解析。在

相关问题 更多 >