django xlsxwriter中的DateTime问题 [英] DateTime issues in django xlsxwriter
问题描述
我正在尝试在我的django视图中创建导出到excel的功能,如下所示:
I am trying to create an export to excel functionality in my django view as follows:
def export_myreport(request, sd, ed):
from xlsxwriter.workbook import Workbook
import cStringIO as StringIO
from django.utils.encoding import smart_str
# create a workbook in memory
output = StringIO.StringIO()
wb = Workbook(output)
bg = wb.add_format({'bg_color': '#9CB640', 'font_color': 'black'})
bg2 = wb.add_format({'bg_color': '#FFFFFF', 'font_color': 'black'})
ws = wb.add_worksheet('My Report')
row_num = 0
summary = MyModel.objects.filter(time__range = (sd, ed)).select_related()
row_num += 2
row = [
smart_str(u"Time"),
smart_str(u"Item"),
smart_str(u"User")
]
for col_num in xrange(len(row)):
ws.write(row_num, col_num, row[col_num], bg)
for s in summary:
row_num += 1
row2 = [
s.time,
s.model_name,
s.user.first_name
]
for col_num in xrange(len(row2)):
ws.write(row_num, col_num, row2[col_num], bg2)
wb.close()
output.seek(0)
response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
response['Content-Disposition'] = "attachment; filename=myreport.xlsx"
return response
但我得到一些日期时间格式的问题!也许我在这里缺少一些东西?
But i am getting some issues with the DateTime formatting! Perhaps something i am missing here?
这是我得到的错误:
TypeError at /myapp/export_myreport/2015-05-01/2015-05-19
can't subtract offset-naive and offset-aware datetimes
编辑:
这是我在我的html中调用url :
This is how i am calling the url in my html:
<a href="export_myreport/{{begindate}}/{{enddate}}" class="btn btn-default pull-right" role="button">Export to XLSX</a>
{{begindate}}
和 {{enddate}}
是角度变量。
推荐答案
Excel,因此XlsxWriter不支持日期/时间的时区。
Excel, and thus XlsxWriter, doesn't support timezones in dates/times.
所以你将需要从datetime中删除或调整时区,然后再传递给XlsxWriter 。
So you will need to remove or adjust the timezone from the datetime before passing it to XlsxWriter.
pytz 文档中的内容如下:
Something like this from the pytz docs:
dt = datetime(2005, 3, 1, 14, 13, 21, tzinfo=utc)
naive = dt.replace(tzinfo=None)
可能这将在Django中更好地处理,而不是调整所有将datetime数据传递给XlsxWriter之前。也许别人可以添加一个建议。
Probably this would be better handled in Django though rather than adjusting all datetime data prior to passing it to XlsxWriter. Maybe someone else can add a suggestion on that.
这篇关于django xlsxwriter中的DateTime问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!