in reply to Win32::OLE Excel how to get milliseonds from date variant?

per the Win32::OLE::Variant docs, Date() only deals with era/year/month/day. The Time() function appears to be the one that handles converting to time with hours/minutes/seconds.

I created a spreadsheet Book1 open in Excel already, where A1 was 2024-01-26 12:34:56.789 and the Excel format "yyyy-MM-dd hh:mm:ss.000" was already applied, and it displayed right in the spreadsheet.

But I couldn't get a modified version of your code to use the $sheetdate->Time("hh:mm:ss.000") to say anything but .000, even when I used manually specified format.

Instead, I just ensured the cell's format was the "yyyy-MM-dd hh:mm:ss.000" (instead of assuming I'd done that in Excel already), and then grabbed the ->Text() from Excel, and that gave me the full string that you appear to want.

use 5.014; # strict, //, s//r use warnings; use Win32::OLE; use Win32::OLE::Const 'Microsoft Excel'; use Win32::OLE::Variant; use Win32::OLE::NLS qw(:LOCALE :DATE); my $Excel = Win32::OLE->GetActiveObject('Excel.Application') || Win32: +:OLE->new('Excel.Application', 'Quit'); # get already active Excel use Data::Dump qw/dd/; my $Book = $Excel->Workbooks('Book1'); my $Sheet = $Book->Worksheets(1); print "Text => ", $Sheet->Range("A1")->Text(); print "Value => ", $Sheet->Range("A1")->Value(); print "{Value} => ", $Sheet->Range("A1")->Value(); my $sheetdate = Variant(VT_DATE, $Sheet->Range("A1")->Value()); print "Date => ", $sheetdate->Date(); print "Date(DATE_LONGDATE) => ", $sheetdate->Date(DATE_LONGDATE); print "Time() => ", $sheetdate->Time(); print "Time(hh:mm:ss) => ", $sheetdate->Time('hh:mm:ss'); print "Time(hh:mm:ss.000) => ", $sheetdate->Time('hh:mm:ss.000'); $Sheet->Range("A1")->{NumberFormat} = "yyyy-MM-dd hh:mm:ss.000"; print $Sheet->Range("A1")->Text(); __END__ Text => 2024-01-26 12:34:56.789 Value => 1/26/2024 12:34:57 PM {Value} => 1/26/2024 12:34:57 PM Date => 1/26/2024 Date(DATE_LONGDATE) => Friday, January 26, 2024 Time() => 12:34:57 PM Time(hh:mm:ss) => 12:34:57 Time(hh:mm:ss.000) => 12:34:57.000 2024-01-26 12:34:56.789

If you need to preserve the format in the spreadsheet, and aren't sure what it is to start with, then set my $saveformat = $Sheet->Range("A1")->{NumberFormat}; before changing it, and change it back to $Sheet->Range("A1")->{NumberFormat} = $saveformat; before you move on.

Replies are listed 'Best First'.
Re^2: Win32::OLE Excel how to get milliseonds from date variant?
by cormanaz (Deacon) on Jan 26, 2024 at 18:43 UTC
    Aha...I didn't know you could request the text instead of value. Thanks!