Updated 2013-10-16 06:33:49 by pooryorick

See http://www.tcl.tk/man/tcl8.6/TclCmd/clock.htm for the formal man page.
clock add timeVal ?count unit...? ?-option value?
clock clicks ?-option?
clock format timeVal ?-option value...?
clock microseconds
clock milliseconds
clock scan inputString ?-option value...?
clock seconds

Beyond that, try the %Q format:
 % clock format [clock scan now] -format %Q
 Stardate 56657.7

See also Star Trek, A little A/D clock

AM The clock command manipulates an integer number that starts at zero at the "epoch" (1 january 1970, IIRC, on UNIX and many other systems). This limits the valid range of dates a bit.

Some experimentation however shows that the range 1 january 1902 to "31 december 2038'' is acceptable on UNIX and Windows. This may not include all dates of birth of now-living people, but it goes a long way. For the Mac this may be a slightly different range (1904-2039).

LV Actually, the range depends on the OS and the version of Tcl. For instance, using Tcl 8.5 on SPARC Solaris, I see:
 $ tclsh8.5
 % clock format [clock scan "January 1, 2040"]
 Sun Jan 01 00:00:00 EST 2040

whereas on the same machine I also see:
 $ tclsh8.4
 % clock format [clock scan "January 1, 2040"]
 unable to convert date-time string "January 1, 2040"
 % clock format [clock scan "Dec 31, 2038"]
 unable to convert date-time string "Dec 31, 2038"

LV To use clock to provide today's date and time formatted, type
        clock format [clock scan now]

 From news:comp.lang.tcl, I see:
 Date: Mon Mar 19 15:41:16 EST 2001
 From: Jeff Hobbs <[email protected]>
 Organization: ActiveState - Programming for the People

 [email protected] wrote:
 Is there a way to do the following by using the clock command:
 If I have a date in the future, for example Mar 26, 2001
 I need to find out what the date for that Saturday is. (Sat Mar 31,  2001)

 Apr 30, 2001 = Sat May 5, 2001
 Mar 28, 2001 = Sat May 5, 2001

 (hobbs) 50 % clock format [clock scan "Saturday" \
        -base [clock scan "Apr 30, 2001"]]
 Sat May 05 00:00:00 Pacific Daylight Time 2001
 (hobbs) 51 % clock format [clock scan "Saturday" \
        -base [clock scan "Mar 28, 2001"]]
 Sat Mar 31 00:00:00 Pacific Standard Time 2001

You can format relative time in seconds to h:m:s format. Just make sure you pretend to be in Greenwich( -gmt 1), otherwise your local timezone may be added. (RS)
  clock format 711 -format %H:%M:%S -gmt 1

See Formatting durations also.

rmax: Is there any chance to tell [clock format] to use another timezone than local or GMT?
 % set env(TZ) GMT ; clock format [clock seconds]
 Wed Jan 30 16:07:47 GMT 2002
 % set env(TZ) GMT+2 ; clock format [clock seconds]
 Wed Jan 30 14:07:52 GMT 2002

"Use" means several different things; here's a different example of clock's intelligence about timezones:
    clock format [clock seconds] -format "%X %x" -locale fi_FI -timezone EET

LV When I try this, on either Tcl 8.4 or 8.5, I get an error:
 $ tclsh8.4
 % clock format [clock seconds] -format "%X %x" -locale fi_FI -timezone EET
 wrong # args: should be "clock format clockval ?-format string? ?-gmt boolean?"
 % srv22 (139) $ tclsh8.5
 % clock format [clock seconds] -format "%X %x" -locale fi_FI -timezone EET
 time zone EET not found

LV Okay, the problem is this -- the -timezone value needs to start with a colon.
 $ tclsh8.5
 % clock format [clock seconds] -format "%X %x" -locale fi_FI -timezone :EET
 15:52:01  9.02.2007

Traditional degrees: clock format can be put to un-timely uses. As degrees especially in geography are also subdivided in minutes and seconds, how's this one-liner for formatting decimal degrees:
 proc dec2deg x {concat [expr int($x)]\u00B0 [clock format [expr round($x*3600)] -format "%M' %S\"" -gmt 1]}

The additional -gmt 1 switch is needed if you happen to live in a non-integer timezone. (RS)

Want to format the modification time of a specific file? Try
 clock format [file mtime "/path/to/my/file"]

where you replace /path/to/my/file with the path you want. Or replace it with a variable containing the path.

To get back, from clock, yesterday's date, use
 clock format [clock scan yesterday]

See "timezone" for a list of recognized timezones.

In the year 2002, the first week reported by %w is 00. To get more natural numbers starting from 1 (and without leading zero), use
 expr [scan [clock format [clock sec] -format %W] %d]+1 ;#RS

This was not the case in the years {1973 1979 1990 1996 2001 2007 2018 2024 2029 2035}, a distance sequence of 6-5-6-11.., where the first week was 01... Hence this cleanup routine, where Jan 1 is always in week 1:
 proc week {date} {
   set week [scan [clock format $date -format %W] %d]
   set year [clock format $date -format %Y]
   if {[lsearch {
        1973 1979 1990 1996 2001 2007 2018 2024 2029 2035
        } $year] < 0} {
        incr week
   set week
 } ;# RS - but better just use %V:

Kevin Kenny wrote on this question in comp.lang.tcl on 2001-01-07, so in week 01 ;-): The format group, %V, yields the ISO8601 fiscal week number. It's inexplicably missing from the documentation in 8.3; this has been fixed in 8.4.

By the way, lots of companies in the US (my employer is NOT one) use a fiscal week numbering system where week 1 begins on the first Sunday of the year rather than on the Monday before the first Thursday.

NEM -- From a question in comp.lang.tcl and a session on the chat, here is a proc for getting the start and end days of a week given a week number (0-51):
 proc dates {date} {
     set date [clock scan "$date weeks" -base [clock scan "01/01/2002"]]
     set st [clock scan "sunday" -base [expr {$date - 436800}]]
     set end [clock scan "saturday" -base $date]
     return [list [clock format $st] [clock format $end]]

 dates 48

 {Sun Dec 01 00:00:00 GMT 2002} {Sat Dec 07 00:00:00 GMT 2002}

NEM -- After some heckling on comp.lang.tcl for not allowing you to specify a year, or what day the week starts on, here is an improvement:
 proc dates {date {year now} {day "Sunday"}} {
      set days [list sun mon tue wed thu fri sat]
      set day [string tolower [string range $day 0 2]]
      if {[string equal $year now]} {
          set year [clock format [clock scan now] -format %Y]
      set date [clock scan "$date weeks" -base [clock scan "01/01/$year"]]
      set st [clock scan $day -base [expr {$date - 436800}]]
      set endday [lsearch $days $day]
      set endday [expr {($endday - 1) % 7}]
      set endday [lindex $days $endday]
      set end [clock scan $endday -base $date]
      return [list $st $end]

It does all the necessary magic. It also returns the numbers rather than pre-formatting them, as this is more flexible. One improvement would be to allow specifying the end day of the week as well (for working weeks, etc). You could do this with an extra parameter, and only calculating the endday if it was not set.

Here is a little procedure that will let you do timestamping accurate to the millisecond. It requires Tcl 8.4 or greater; while 8.3 supports [clock clicks -milliseconds], the 'clicks' and the 'seconds' are not properly synchronized on all platforms. The procedure was originally sent by Kevin Kenny on comp.lang.tcl. I have modified it a bit so that it can give back the second and millisecond information separately to the caller. EF
  package require Tcl 8.4
  proc timestamp { { tv_sec_p "" } { tv_msec_p "" } } {
    if { $tv_sec_p != "" } {
        upvar $tv_sec_p secs
    if { $tv_msec_p != "" } {
        upvar $tv_msec_p fract

    set secs [clock seconds]
    set ms [clock clicks -milliseconds]
    set base [expr { $secs * 1000 }]
    set fract [expr { $ms - $base }]
    if { $fract >= 1000 } {
        set diff [expr { $fract / 1000 }]
        incr secs $diff
        incr fract [expr { -1000 * $diff }]

    return $secs.[format %03d $fract]

MH (2005-10-04) Never mind.. Should have tested it first. Works as advertised :-)

EF (2007-09-26) Procedure above slightly modified to fix a tiny bug reported by Tim Tomkinson. Thanks.

JYL I needed a calculator for the difference between two timestamps as produced by the above, so here is the code I came up with:
   proc timestampDiff {ts1 ts2} {
    foreach {s1 f1} [split $ts1 '.'] {}
    foreach {s2 f2} [split $ts2 '.'] {}
    set f1 [string trimleft $f1 '0']
    set f2 [string trimleft $f2 '0']

    # Unpredictable results if the timestamp s2.f2
    # precedes s1.f1!!!

    set fd [expr {$f2 - $f1}]
    if {$fd < 0} {
        set fd [expr {1000 + $fd}]
        incr s2 -1
    set sd [expr {$s2 - $s1}]
    return $sd.[format %03d $fd]

Relative time access by hours, minutes, seconds: If you work with relative times in seconds, you can extract its components with [clock scan] and [clock format], but you can also do it with direct arithmetics (RS):
 proc time'h time {expr {($time%86400)/3600}}
 proc time'm time {expr {($time%3600)/60}}
 proc time's time {expr {$time%60}}

KBK (2004-11-29) wishes to open a discussion on the subject of Parsing ISO8601 dates and times

DKF (2005-05-30): Working out someone's age can be tricky. Luckily, the clock command (with some helping expr trickery) can provide a lot of support for this.
 # Date-of-birth (in seconds relative to epoch) in $dob
 foreach {Ynow CMPnow} [clock format [clock seconds] -format "%Y 1%m%d"] {}
 foreach {Ydob CMPdob} [clock format $dob -format "%Y 1%m%d"] {}
 set ageInYears [expr { $Ynow-$Ydob-($CMPnow<$CMPdob) }]

KBK: "http://www.cl.cam.ac.uk/~mgk25/uts.txt is Tcl's model of time ..."

MG See also Bag of number/time spellers

Draft of text which might be easier for beginners to read

Clock is a tool for, you guessed it, looking at a clock. Your computer has a little clock inside of it that ticks off all of the seconds of the day and night. Computers being such math whizzes, like to think about the time of day in seconds. In fact, with microsoft windows machines, that number of seconds they keep counting, is how many have passed since midnight of the turning of the year between 1969 and 1970. The span of years over which computers count the seconds has been named in dramatic language: "the epoch."

In fact, checking my computer's time, right now, I see that it says that there have been one billion, one hundred fifty million seconds which have passed in this epoch, so far. 1,157,998,843 to be exact.

And if you're curious, computers do take into account the extra seconds for leap day, every four years.

Check what time it is on your computer:
 clock seconds

Because humans' minds are quite boggled by such a large number, TCL makes it easy to read the time in a way we are more accustomed to.
 set unweildytime [clock seconds]
 clock format $unweildytime -format %x
 clock format $unweildytime -format %r

Did you see what happened there? First we had to get the gargantuan number of seconds... and then we had to give that number to our clock tool again. Unfortunately, we have to use the word format twice on the same line; that makes it a bit harder to read. And what is that percentage thingy? That is how we tell TCL the pattern we wish to see things in.

If you want ALL the details, here are the patterns which you can request:

  • %a -- the abbreviated english language weekday name (Mon, Tue, etc.).
  • %A -- the full english weekday name (Monday, Tuesday, etc.).
  • %b -- an abbreviated month name (Jan, Feb, etc.).
  • %B -- the full month name.
  • %C -- the first two digits of the four-digit year (19 or 20).
  • %d -- day of month (01 - 31).
  • %e -- day of month (1 - 31) with no leading zeros.
  • %h -- the abbreviated month name.
  • %H -- the hour in 24-hour format (00 - 23).
  • %I -- the hour in 12-hour format (01 - 12).
  • %j -- the numbered day of the year (001 - 366).
  • %k -- the hour in 24-hour format, without leading zeros (0 - 23).
  • %l -- the hour in 12-hour format, without leading zeros (1 - 12).
  • %m -- The month number (01 - 12).
  • %M -- minute (00 - 59).
  • %p -- AM/PM indicator.
  • %S -- seconds (00 - 59).
  • %u -- The day of the week as a number (Monday = 1, Sunday = 7).
  • %U -- the numbered week of the current year (00 - 52). Here, Sunday is considered the first day of the week.)
  • %w -- weekday as a number (Sunday = 0, Saturday = 6).
  • %W -- the week of the year (00 - 52), Monday is the first day of the week.
  • %y -- this year without the century noted (00 - 99).
  • %Y -- the complete year (e.g. 1990)
  • %Z -- Your timezone name ;-)

There are even several pre set patterns you can choose from -- an easy complete datestamp.

  • %D -- Date as %m/%d/%y.
  • %T -- Time as %H:%M:%S.
  • %R -- Time as %H:%M.
  • %c -- Date and time as your computer normally says them to you. On Unix/macintosh the format for date and time is the default "C" locale: "%a %b %d %H:%M:%S %Y". On microsoft windows, this pattern is specified in the Regional Options control panel settings.
  • %x -- Just the date as your computer is accustomed to writing it. Unix/Macintosh form is: "%m/%d/%y".
  • %X -- The twenty four hour clock. The Unix/Macintosh form is "%H:%M:%S".
  • %r -- The am/pm clock. For Unix/Macintosh, this is "%I:%M:%S %p".

You even get the option to insert whitespace

  • %t -- Insert a tab.
  • %n -- Insert a newline.
  • %% -- type the percentage sign, itself

Assorted other patterns:

  • %g -- The ISO8601 year number corresponding to the ISO8601 week (%V), expressed as a two-digit year-of-the-century, with leading zero if necessary.
  • %G -- The ISO8601 year number corresponding to the ISO8601 week (%V), expressed as a four-digit number.
  • %Q -- For testing only.
  • %V -- Week of year according to ISO-8601 rules. Week 1 of a given year is the week containing 4 January.
  • %s -- Count of seconds since the beginning of the epoch, expressed as a decimal integer (yes, this is redundant!)

 proc ddate {dt} {
        clock format [clock scan $dt]

 % ddate "2007-1-12 11:00am"
 Fri Jan 12 11:00:00 EST 2007
 % ddate {1 january 1900}
 Mon Jan 01 00:00:00 EST 1900
 % ddate 1/1/200
 Tue Jan 01 00:00:00 EST 0200
 % ddate 1/1/100
 Wed Jan 01 00:00:00 EST 0100
 % ddate 1/1/99
 Fri Jan 01 00:00:00 EST 1999

LV I'm confused by this code:
 % set n [clock scan "12-1-2007 11:00am"]
 % puts [clock format $n]
 Thu Jun 29 11:00:00 EDT 2017

Why 2017? There doesn't appear, to me, to be anything in the first string that would be misinterpreted as 2017. I could understand if it were 2012, or even 2001... it would make me sad, but at least I could see how that was reached.

schlenk Simple: The year 12 of this century, add one month and 2007 days and you get a date in 2017.

slebetman: I just get:
 unable to convert date-time string "12-1-2007 11:00am"

LV So why is a date in the format listed in the documentation as a valid month, day, year format being treated as some sort of calculation instead?

LV Ah -- because the date was input wrong! The format accepted is yyyy-mm-dd:
 % clock format [clock scan "2007-1-12 11:00am"]
 Fri Jan 12 11:00:00 EST 2007

Here's how to get the first day of the current month.
clock format [clock scan 1 -format %d]

Here's how to get the last day of the current month.
clock format [clock scan 0 -format %d -base [clock add [clock seconds] 1 month]]

Kevin tells [1] in a Reddit thread a little about the wonderfulness [2] that clock became with 8.5.

AMG: The Tcl 8.4 synopsis for the [clock] command: "Obtain and manipulate time" [3]. Godlike.

See also edit