Home » excel » Converting time with Python and DataNitro in Excel

Converting time with Python and DataNitro in Excel

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a list of times in h:m format in an Excel spreadsheet, and I’m trying to do some manipulation with DataNitro but it doesn’t seem to like the way Excel formats times.

For example, in Excel the time 8:32 is actually just the decimal number .355556 formatted to appear as 8:32. When I access that time with DataNitro it sees it as the decimal, not the string 8:32. If I change the format in Excel from Time to General or Number, it converts it to the decimal (which I don’t want). The only thing I’ve found that works is manually going through each cell and placing ‘ in front of each one, then going through and changing the format type to General.

Is there any way to convert these times in Excel into strings so I can extract the info with DataNitro (which is only viewing it as a decimal)?

How to&Answers:

If .355556 (represented as 8:32) is in A1 then =HOUR(A1)&":"&MINUTE(A1) and Copy/Paste Special Values should get you to a string.

Answer:

Ideally it seems that you probably don’t want to change the way that excel keeps the data (Obviously depending on your use case).

If that is the case there is excellent post How do I read a date in Excel format in Python? that explains how to convert the float to a python date time object. Specifically the script by @John Machin works great.

import datetime

def minimalist_xldate_as_datetime(xldate, datemode):
    # datemode: 0 for 1900-based, 1 for 1904-based
    return (
        datetime.datetime(1899, 12, 30)
        + datetime.timedelta(days=xldate + 1462 * datemode)
        )

Note his disclaimer “Here’s the bare-knuckle no-seat-belts use-at-own-risk version:” I have used it with no problems.