'module' object has no attribute 'now' will trying to create a CSV

这一生的挚爱 提交于 2020-02-17 05:59:43

问题


Hello I'm having problems importing to csv, I get that error, the problem is that I have the same code running in other machine and it runs perfectly. What am I missing do I need to install an other library for this?.

def exportar_a_csv_grl(request):
    #Fecha actual
    hoy = datetime.now().date()
    #Creado el:
    creado_hoy = hoy.strftime("%m/%d/%Y")
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment;filename="Reporte de Miembros ' +      creado_hoy + '.csv"'
response['Content-Type'] = 'text/csv; charset=utf-8'
response.write("\xEF\xBB\xBF")

writer = csv.writer(response)
miembros = Miembro.objects.all().extra(select={'miem_monto': "aplicacionmediexcel_miembro_monto.monto"},
                                       tables=["aplicacionmediexcel_miembro_monto"], where=[
        """aplicacionmediexcel_miembro.id=aplicacionmediexcel_miembro_monto.miembro_id"""])
#.extra(select = {'precio':'''select aplicacionmediexcel_miembro_monto.monto from aplicacionmediexcel_miembro_monto, aplicacionmediexcel_miembro where  aplicacionmediexcel_miembro.id = aplicacionmediexcel_miembro_monto.miembro_id'''})
miembros_colec = Miembro_colec.objects.all().extra(
    select={'miem_monto': "aplicacionmediexcel_colectivo_miembro_monto.monto"},
    tables=["aplicacionmediexcel_colectivo_miembro_monto"],
    where=["""aplicacionmediexcel_miembro_colec.id=aplicacionmediexcel_colectivo_miembro_monto.miembro_colec_id"""])
dependientes = Dependiente.objects.all()
dependientes_colec = Dependiente_colec.objects.all()
writer.writerow(['Creado el:             ' + creado_hoy + ' '])
writer.writerow([''])
#csv_data = (
#   ('ID Miembro', 'Apellido Paterno', 'Nombre', 'MI', 'Numero de Seguro Social', 'Tipo de contratacion','Tier', 'Tipo de dependiente', 'Fecha de nacimiento', 'Edad', 'Sexo', 'Estado Civil', 'Correo Electronico', 'Domicilio', 'Ciudad','Estado', 'Codigo Postal', 'Telefono', 'Idioma', 'Region de servicio', 'Medico', 'Fecha Efectiva', 'Tipo Plan', 'Grupo', 'Monto'),
#)
writer.writerow(
    ['ID Miembro', 'Apellido Paterno', 'Nombre', 'MI', 'Número de Seguro Social', 'Tipo de contratación',
     'Tier', 'Tipo de dependiente', 'Fecha de nacimiento', 'Edad', 'Sexo', 'Estado Civil', 'Correo Electrónico',
     'Domicilio', 'Ciudad',
     'Estado', 'Código Postal', 'Teléfono', 'Idioma', 'Región de servicio', 'Médico', 'Actividad', 'Fecha Efectiva',
     'Fecha Renovación', 'Tipo Plan', 'Grupo', 'Monto'])

#t = loader.get_template('my_template_name.txt')
#c = Context({
#   'miembros': miembros,
#})
#response.write(t.render(c))

回答1:


You probably have

import datetime

change that to

from datetime import datetime

Demo:

>>> import datetime
>>> datetime.now()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'now'
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2013, 10, 7, 13, 57, 18, 456504)
>>> 

Also, you will run into issues due to indentation. Please fix those.




回答2:


When you do

import datetime

you have to use

>>> datetime.datetime.now()
datetime.datetime(2016, 12, 14, 1, 15, 58, 606802)

otherwise if you import like

>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2016, 12, 14, 1, 17, 31, 772406)

But on some machine you could refer to wrong datetime module because of sys.path , instead of doing from datetime import datetime or import datetime make a habbit of using

from datetime import datetime as dt



回答3:


i had the same problem when i used

from datetime import datetime,date,timedelta
import pytz
utc=pytz.UTC
today = datetime.now().replace(tzinfo=utc)

Solution for this which i will suggest is to import all the dependencies

from datetime import *
import pytz
utc=pytz.UTC
today = datetime.now().replace(tzinfo=utc)


来源:https://stackoverflow.com/questions/19231458/module-object-has-no-attribute-now-will-trying-to-create-a-csv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!