Date and time that include Milliseconds

Hi I would like to include in my detailed log of app the time stamp with milliseconds when a VerboseLog() handler is called.
At the moment I can write something like YYYYMMDD-HHMMSS but i miss the milliseconds.
Anyone has a solution using pure AppleScript or Asoc?

Stefano - Ame

I don’t know of a way to do it in “pure” Applescript, but you can do it with a do shell script and Perl.

set UNIXtime to do shell script "perl -e 'use Time::HiRes qw(time); print time'"

With ASObjC:

use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"

set now to current application's class "NSDate"'s |date|()
set dateFormatter to current application's class "NSDateFormatter"'s new()
tell dateFormatter to setDateFormat:("yyyyMMdd-HHmmss.SSS")
set timeStamp to (dateFormatter's stringFromDate:(now)) as text

However, I don’t imagine the clock on your computer will be that accurately set. :slight_smile:

Hi Nigel,

W o n d e r f u l ! ! !
Exactly what I need. Thank you!!!

Stefano

With AppleScript Toolbox:

AST format date "yyyyMMdd-HHmmss.SSS"

With Python:


do shell script "
/usr/bin/python <<END
from datetime import datetime
print datetime.now()
END"

Or if you want the Python to spit out the requested formatting instead of doing it in Applescript (Python formatting code is shorter)


do shell script "
/usr/bin/python <<END
from datetime import datetime
now = datetime.now()
print '%04d%02d%02d-%02d%02d%02d.%d' % (now.year,now.month, now.day,now.hour,now.minute,now.second, int(round((float(now.microsecond)/1000), 0)))
END"

This is rounding the fractional seconds to three decimal places (milliseconds) as requested.

If you want the full microseconds:

do shell script "
/usr/bin/python <<END
from datetime import datetime
now = datetime.now()
print '%04d%02d%02d-%02d%02d%02d.%d' % (now.year,now.month, now.day,now.hour,now.minute,now.second, now.microsecond)
END"