سؤال

This is my code:

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

This works on my OSX dev environment (virtualenv env django 1.5)

But on my production server (ubuntu 12.04 virtualenv django 1.5) it does not work with this error:

Django Version: 1.5.1
Exception Type: TypeError
Exception Value:    
must be string, not datetime.datetime
Exception Location: /var/www/webapps/cirostats/products/templatetags/product_tags.py in show_main_chart, line 41

Line 41 is

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

I cant figure out why works on the one environment and not the other? Who is wrong here, the dev or prod?

Prod : Python 2.7.3
Dev: Python 2.7.1

MORE:

This is how report is made:

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')
هل كانت مفيدة؟

المحلول

In your production environment, i['month'] is already a datetime.datetime object:

>>> 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

So to find the difference between your production and development environments, you'll have to trace what produces report and find out why one environment produces strings, and the other produces datetime.datetime objects instead.

If you are using datetime operations on your server backend, take into account that some SQL servers support native datetime arithmetic, but SQLite (the database you usually develop against) does not. PostgreSQL will produce datetime objects, SQLite produces strings.

You'll either want to switch how you handle dates here based on your database settings, or detect if you already have a datetime object and skip parsing.

نصائح أخرى

strptime results in a datetime object which is, in your debug environment printable, for production you need to change it to:

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

But since you strptime is normally used to convert a date/time to a datetime object from a string I am not sure why you are not just using the string directly. i.e. 'date':i['month']

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top