Jump to content
AndyS01

Need to convert Excel time values to actual time string

Recommended Posts

AndyS01

I have an Excel file that I want to read and display the dates and times from each row, but the time value is a small decimal number.

I want to convert that number to an actual time string.

The Excel data is:

Col A       Col B    Col C
6/17/2016   1:00:00  Date is 6/17/2015, time is 1:00:00 AM
6/17/2016   1:00:01  Date is 6/17/2015, time is 1:00:01 AM
6/17/2016   2:00:00  Date is 6/17/2015, time is 2:00:00 AM
6/17/2016   3:00:00  Date is 6/17/2015, time is 3:00:00 AM

My test code is:

#include <Excel.au3>

#NoTrayIcon
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=THTracker.ico
#AutoIt3Wrapper_UseUpx=n
#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6
#AutoIt3Wrapper_UseX64=N
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

test()
Func test()
    Local $fn, $ffn, $obj, $ndx, $ndx2, $ar

    $fn = "C:\Util\AutoIT-src\myStuff\THTracker\Copy of 2016 Easton 100.xlsx"
    ConsoleWrite("+++: $fn ==>" & $fn & "<==" & @CRLF)

    $ffn = FileGetShortName($fn, 1)
    ConsoleWrite("+++: $ffn ==>" & $ffn & "<==" & @CRLF)

    $obj = _ExcelBookOpen($ffn, 0, 1) ; open excel in the background
    ConsoleWrite("+++: isObj($obj) = " & IsObj($obj) & @CRLF)

    $ar = _ExcelReadSheetToArray($obj)

    _ExcelBookClose($obj)

    ConsoleWrite("+++: $ar[0][0] = " & $ar[0][0] & @CRLF)
    ConsoleWrite("+++: $ar[0][1] = " & $ar[0][1] & @CRLF)

    For $ndx = 1 To $ar[0][0]
        ConsoleWrite("+++: Date = " & $ar[$ndx][1] & @CRLF)
        ConsoleWrite("+++: Time = " & $ar[$ndx][2] & @CRLF)

        For $ndx2 = 1 To $ar[0][1] - 1
            ConsoleWrite("+++: [" & $ndx & "][" & $ndx2 & "] = " & $ar[$ndx][$ndx2] & @CRLF)
        Next
    Next

EndFunc   ;==>test

The console output is:

+++: $fn ==>C:\Util\AutoIT-src\myStuff\THTracker\Copy of 2016 Easton 100.xlsx<==
+++: $ffn ==>C:\Util\AUTOIT~1\myStuff\THTRAC~1\COPYOF~1.XLS<==
+++: isObj($obj) = 1
+++: $ar[0][0] = 4
+++: $ar[0][1] = 4
+++: Date = 20160617000000
+++: Time = 0.0416666666666667
+++: [1][1] = 20160617000000
+++: [1][2] = 0.0416666666666667
+++: [1][3] = Date is 6/17/2015, time is 1:00:00 AM
+++: Date = 20160617000000
+++: Time = 0.0416782407407407
+++: [2][1] = 20160617000000
+++: [2][2] = 0.0416782407407407
+++: [2][3] = Date is 6/17/2015, time is 1:00:01 AM
+++: Date = 20160617000000
+++: Time = 0.0833333333333333
+++: [3][1] = 20160617000000
+++: [3][2] = 0.0833333333333333
+++: [3][3] = Date is 6/17/2015, time is 2:00:00 AM
+++: Date = 20160617000000
+++: Time = 0.125
+++: [4][1] = 20160617000000
+++: [4][2] = 0.125
+++: [4][3] = Date is 6/17/2015, time is 3:00:00 AM
+>12:52:23 AutoIt3.exe ended.rc:0
+>12:52:23 AutoIt3Wrapper Finished.
>Exit code: 0    Time: 1.206

Note that the time values [n][2] are all decimal values like  0.0416666666666667, 0.125, etc.

Share this post


Link to post
Share on other sites
water

Excel stores the date/time as a number. The fractional part is the time.
Details can be found here: https://www.autoitscript.com/wiki/Excel_UDF#Date_and_Time


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites
water

You could use the Excel date functions to translate date and time in columns A and B to the string in column C:

https://support.office.com/en-us/article/Date-and-time-functions-reference-fd1b5961-c1ae-4677-be58-074152f97b81


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites
AndyS01

I found that the date was stored as yyyymmdd  (20000119000000)

The time is stored as a decimal number 

Also, I cannot modify the spreadsheets, so I have to go with what I get.

From the Excel UDF doc:
 

Quote

The fractional portion of the number represents the fractional portion of a 24 hour day. For example, 6:00 AM is stored as 0.25,

How can I convert this fractional time of day to a hh:mm:ss string?

 

Share this post


Link to post
Share on other sites
water

Something like this:

#include <Date.au3>

Local $iTimeStamp = 42465.7260416667 ;= 2016-04-05 17:25:30" = yyyy-mm-dd hh:mm:ss
Local $iDec = $iTimeStamp - Int($iTimeStamp)
Local $Date = _DateAdd("D", Int($iTimeStamp), "1899/12/30 00:00:00")
Local $DateTime = _DateAdd("s", Int($iDec * 24 * 3600), $Date)
MsgBox(0, "Results", "Timestamp: " & $iTimeStamp & " = " & _
StringRegExpReplace($DateTime, "(\d{4})/(\d{2})/(\d{2}) (.*)", "\3-\2-\1 \4") & " in dd/mm/yyyy hh:mm:ss")

 


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites
AndyS01

As the cell was only a time value, here's what I came up with:

_GetTime("01:02:03")
_GetTime("05:06")
_GetTime(0.0416666666666667)

Func _GetTime($sCellText)
    Local $ampm, $time = ""

    If ($time == "") _
            And (StringRegExp($sCellText, "^\d{1,2}+[:]\d{1,2}+[:]\d{1,2}$")) Then
        $time = $sCellText; Syntax was hh:mm:ss
    EndIf

    If ($time == "") _
            And (StringRegExp($sCellText, "^\d{1,2}+[:]\d{1,2}+$")) Then
        $time = $sCellText & ":00"; Syntax was hh:mm
    EndIf

    If ($time == "") _
            And ($sCellText <> "") _
            And (((1 + $sCellText) - 1) == $sCellText) Then
        Local $iNum, $x, $hh, $mm, $ss
        ; Cell data was a decimal number like 0.0416666666666667

        $iNum = 24 * 60 * 60
        $x = $iNum * $sCellText
        $ss = Floor(Mod($x, 60))
        $x = Floor($x / 60)
        $mm = Mod($x, 60)
        $hh = Floor($x / 60)

        If ($ss == 59) Then
            ; Fix rounding errors resulting in secs = 59
            $ss = 0
            $mm += 1
            If ($mm == 59) Then
            If ($mm == 59) Then
                $mm = 0
                $hh += 1
            EndIf
        EndIf

        If ($hh > 12) Then ; Change from military time
            $hh -= 12
            $ampm = "PM"
        ElseIf ($hh == 12) Then
            $ampm = "PM"
        Else
            $ampm = "AM"
        EndIf

        $time = StringFormat("%d:%02d %s", $hh, $mm, $ampm)
    EndIf

    ConsoleWrite("+++: $sCellText ==>" & $sCellText & "<==" & @CRLF)
    ConsoleWrite("+++: $time      ==>" & $time & "<==" & @CRLF)
    consolewrite(@crlf)

    Return ($time)
EndFunc   ;==>_GetTime

Thanks for your help.

 

Share this post


Link to post
Share on other sites
water

:)


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites
jchd

@AndyS01,

Beware that == is a case-sensitive string comparison. You shouldn't use this to compare numbers.

; Cell data was a decimal number like 0.0416666666666667
ConsoleWrite(StringRight(_DateAdd('s', 86400 * $sCellText, '2000/01/01 00:00:00'), 8) & @LF)

 


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites
AndyS01

Thanks for the heads-up, it's a bad habit I've gotten into.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • Gowrisankar
      By Gowrisankar
      Dear members of the forum,
      I need to open excel files that may or may not need a password and finally move the files that needs password to manual queue.
      Is there a fastest way to do this?
       
      PS: I have a huge respect for the rules of this forum. I am not asking assistance to override any security measure. I just need to segregate the files that needs passwords.
    • MrCheese
      By MrCheese
      Hi guys,
      without including everything (unless you want it)
      I am copying data from a table in chrome and wanting to paste it into excel.
      Copying in Chrome works.
      I can paste it into the field i want by emulating goto -> ctrl V:
      WinActivate($dataload) WinWaitActive($dataload) Sleep(500) $oWorkbook1.Sheets("ItemReturn").Activate Sleep(500) $msg = "Measuring Sheet" conwrite() ttips2() Local Const $xlUp = -4162 With $oWorkbook1.ActiveSheet ; process active sheet $oRangeLast = .UsedRange.SpecialCells($xlCellTypeLastCell) ; get a Range that contains the last used cells $iRowCount = .Range(.Cells(1, 1), .Cells($oRangeLast.Row, "B")).Rows.Count ; get the the row count for the range starting in row/column 1 and ending at the last used row/column $iLastCell = .Cells($iRowCount + 1, "B").End($xlUp).Row ; start in the row following the last used row and move up to the first used cell in column "B" and grab this row number EndWith $NewStartCell = $iLastCell + 2 $msg = "moving to location" conwrite() ttips2() Sleep(250) Send("^g") WinWait("Go To") Sleep(100) Send("B" & $NewStartCell) Sleep(100) Send("{ENTER}") Sleep(500) Send("^v")  
      But, I want to use _excel_rangecopypaste, pasting from the clipboard
      _Excel_RangeCopyPaste($oWorkbook1.ActiveSheet, default, "B" & $NewStartCell,default,$xlPasteValuesAndNumberFormats) If @error Then Exit MsgBox($MB_SYSTEMMODAL, "Excel UDF: _Excel_RangeCopy Example 2", "Error pasting cells." & @CRLF & "@error = " & @error & ", @extended = " & @extended) however, this gives me error 4 , extended@:  -2147352567
      How can i fix this or find out how to debug this error?
       
      Thanks
    • Simpel
      By Simpel
      Hi.
      I try to figure out who is using a excel workbook which I can only open "read only". I use this code:
      #include <Array.au3> #include <Excel.au3> Local $sFile = ; excel file with path on a network drive Local $oExcel = _Excel_Open(True, True) Local $oTabelle = _Excel_BookOpen($oExcel, $sFile) Local $aUsers If IsObj($oTabelle) Then $aUsers = $oTabelle.UserStatus _ArrayDisplay($aUsers) EndIf If I am the one allowed to write to the excel file (I'm the first one who opened it) then I will get an array with myself:

      If my collegue opened the excel file first and I run the code I get the following error message:
      "H:\_Conrad lokal\Downloads\AutoIt3\_COX\Tests\test.au3" (9) : ==> The requested action with this object has failed.: $aUsers = $oTabelle.UserStatus $aUsers = $oTabelle^ ERROR The excel file is on a network drive. Is that's the problem?
      Regards, Conrad
    • robertocm
      By robertocm
      change linked image paths in excel 2007 Open XML Files with AutoIt and 7-zip:
      #include <File.au3> ;Change this Local $sFind = "C:\Users\MyUserName\Documents\MyImageFolder\My%20Image1.png" Local $sReplace = "C:\Users\ANOTHERUSERNAME\Documents\AnotherImageFolder\My%20Image1.png" Local Const $sMessage = "Directory to change excel image paths" Local $sFileSelectFolder = FileSelectFolder($sMessage, "") Local $sTempDir = @ScriptDir & "\testdir" ;Required 7-zip Local $PathZipProgram = @ProgramFilesDir & "\7-Zip\" If Not(FileExists($PathZipProgram & "\7z.exe")) Then MsgBox(16, "", "7z.exe not found in path " & $PathZipProgram) Exit EndIf ;look for excel files in selected directory and all subdirectories Local $SFileList = _FileListToArrayRec($sFileSelectFolder, "*.xls.;*.xlsm", $FLTAR_FILES, $FLTAR_RECUR, $FLTAR_NOSORT, $FLTAR_FULLPATH) If Not @error Then For $i = 1 To $SFileList[0] DirRemove($sTempDir, 1) ;use x command to keep the folder stucture, -aoa Overwrite All existing files without prompt, use -r to unzip the subfolders from the zip file RunWait('"' & $PathZipProgram & '7z.exe" x -aoa -r "' & $SFileList[$i] & '" -o"' & $sTempDir & '" -y', $PathZipProgram, @SW_HIDE) __ReplaceImagePaths($sTempDir, $sFind, $sReplace) RunWait('"' & $PathZipProgram & '7z.exe" a -r "' & $SFileList[$i] & '" "' & $sTempDir & '\*" -tzip -y', $PathZipProgram, @SW_HIDE) Next Else MsgBox(16, "Error", "No files were found in the folder specified.") EndIf DirRemove($sTempDir, 1) Func __ReplaceImagePaths($sTempDir, $sFind, $sReplace) ;List all files with .xml.rels extension in the directory \xl\drawings\_rels Local $aFileList = _FileListToArray($sTempDir & "\xl\drawings\_rels", "*.xml.rels", 1, True) If @error = 1 Then ;MsgBox (0, "", "Path was invalid") SplashTextOn("Title", "Path was invalid", -1, -1, -1, -1, 1, "", 24) Sleep(2000) SplashOff() Exit EndIf If @error = 4 Then ;MsgBox (0, "No files", "No files were found") SplashTextOn("Title", "No files were found", -1, -1, -1, -1, 1, "", 24) Sleep(2000) SplashOff() Exit EndIf Local $iRetval ;Loop through the array For $i = 1 To $aFileList[0] $iRetval = _ReplaceStringInFile($aFileList[$i], $sFind, $sReplace) Next EndFunc  
      Some references:
      https://stackoverflow.com/questions/37145369/change-path-to-picture-links-in-excel http://www.jkp-ads.com/Articles/Excel2007FileFormat.asp EDITED:
      Note: it seems that if User Account Control (UAC) is enabled then 7zip is unable to overwrite the destination file (using the same name).
      In this case, a possible solution would be to rename the original excel file before (see _PathSplit in help file).
      In my case i prefer just to disable UAC
    • SOF-TECH
      By SOF-TECH
      Dear all,
      Can someone show  me how to en hance the below function to write in CSV  into column  and rows the input values ? 
      I am getting this result: 

      I would like the result to be as this 

      From A1:C1 is for headers
      From A2:C2 is for input Data
      Global Const $GUI_EVENT_CLOSE = -3 $sDataFilePath = @ScriptDir & "\Records.csv" #region ### START Koda GUI section ### Form= $Form1 = GUICreate("Demo1: New Record", 580, 115) $Input1 = GUICtrlCreateInput("", 10, 30, 270, 21) $Input2 = GUICtrlCreateInput("", 300, 30, 270, 21) $Input3 = GUICtrlCreateInput("", 10, 80, 270, 21) $Label1 = GUICtrlCreateLabel("Name:", 10, 10, 35, 17) $Label2 = GUICtrlCreateLabel("ID:", 300, 10, 18, 17) $Label3 = GUICtrlCreateLabel("Phone No:", 10, 60, 55, 17) $Button1 = GUICtrlCreateButton("Save to CSV", 450, 70, 120, 30) GUISetState(@SW_SHOW) #endregion ### END Koda GUI section ### While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case $Button1 _ExportData() MsgBox(64, @ScriptName, "Record Saved.") EndSwitch WEnd Func _ExportData() If Not FileExists($sDataFilePath) Then FileWriteLine($sDataFilePath, "Name;ID;Phone No.;") EndIf For $i = $Input1 To $Input3 FileWrite($sDataFilePath, GUICtrlRead($i) & ";") Next FileWriteLine($sDataFilePath, "") EndFunc ;==>_ExportData May be Excel UDF has be to be added but I can manage that my self  
      Thank you in advance
×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.