I am new, just downloaded xlrd/xlwt yesterday.
Am trying to figure out how to work with dates.
Can someone help me correctly use xldate_from_date_tuple to convert a
date into Excel format?
>>> import xlrd
>>> book = xlrd.open_workbook("C:\\working\\" + "Test.xls")
>>> sheet = book.sheet_by_name("I5")
>>> dateCell = sheet.cell(2,0)
>>> dateCell.value
39469.0
>>> xlrd.xldate_as_tuple(dateCell.value, 0)
(2008, 1, 22, 0, 0, 0)
>>> xlrd.xldate_from_date_tuple((2008,1,22), 0)
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
AttributeError: 'module' object has no attribute
'xldate_from_date_tuple'
>>>
Thanks!
Nancy
Hi Nancy,
Welcome to xlrd, xlwt, and this group!
Try this:
>>> xlrd.xldate.xldate_from_date_tuple((2008,1,22), 0)
39469.0
The xldate_from_*_tuple functions are not available at the top level --
they were overlooked and this has remained so because you are the first
to bring this to my attention.
Those functions are in any case little used as far as I know. When
writing xls files using xlwt, you don't need to provide an xldate; you
provide a datetime.(datetime|date|time) instance and xlwt handles things
from then on.
Cheers,
John
I did get xlrd.xldate.xldate_from_date_tuple((2008,1,22), 0) to work as
you showed.
And I do understand why this isn't really used.
So now I want to write a date using xlwt.
What is the right way to do this?
I get an invalid date '#######' in the worksheet but I want 2/4/09 or
something similar.
>>> wb = xlwt.Workbook()
>>> ws = wb.add_sheet("foo")
>>> style.num_format_str = 'M/D/YY'
>>> dt = time.mktime((2009, 2, 4,0,0,0,0,0,0))
>>> ws.write(2,1,dt,style)
>>> wb.save("C:\\working\\bar.xls")
-Nancy
> So now I want to write a date using xlwt.
> What is the right way to do this?
> I get an invalid date '#######' in the worksheet but I want 2/4/09 or
> something similar.
>
>>>> wb = xlwt.Workbook()
>>>> ws = wb.add_sheet("foo")
>>>> style.num_format_str = 'M/D/YY'
Have you tried easyxf yet?
>>>> dt = time.mktime((2009, 2, 4,0,0,0,0,0,0))
>>>> ws.write(2,1,dt,style)
>>>> wb.save("C:\\working\\bar.xls")
Recall what I wrote in the previous message:
"""
When writing xls files using xlwt, you don't need to provide an xldate;
you provide a datetime.(datetime|date|time) instance and xlwt handles
things from then on.
"""
time != datetime
>>> import time
>>> dt = time.mktime((2009, 2, 4,0,0,0,0,0,0))
>>> dt
1233669600.0
That is a float object containing seconds since 1970-01-01T00:00:00. If
for some reason you are desperate to supply a float, it needs to be an
xldate. An xldate is days since read_the_xlrd_docs. The only use case
for supplying a float that I'm aware of is when you've just dug the
xldate out of an xls and you want to avoid converting it to a
datetime.datetime instance and back again.
HTH,
John