Tcl script to calculate a duration - tcl

I need to create a script whithin I can calcute a durations here an example :
assign duration1 5.hours
assign duration2 4.minutes
assign duration3 10.seconds
assign seconds [calc_duration [getVar duration1] + [getVar duration2] + [getVar duration3]]*
I want to get as a respons (seconds) for the example I would have "18250" seconds.
can you please help me with this.
Thanks.

The clock add command can do calculations with durations, but it needs a base time to work with. That's important because, for example, not all months are the same number of days long, and not all days are the same number of hours because of DST rules (which are themselves not the same every year). If you're only working with the small units and not too many of them, you can ignore this and use 0 (the start of the Unix epoch) as the base time.
set seconds [clock add 0 5 hours 4 minutes 10 seconds]
But if you're working with longer amounts of time, you'll need to be more careful. clock add still has the tools, but you'll have to choose the base timestamp correctly and specify your locale of interest.
# You're really supposed to scan with a format, but I'm lazy
set baseTimestamp [clock scan "4/4/2022 10:30 EST"]
set timezone :America/New_York; # EST/EDT
set timeBits {5 months 4 days 3 hours 2 minutes 1 second}
# Do the time arithmetic
set targetTimestamp [clock add $baseTimestamp {*}$timeBits -timezone $timezone]
# Convert into an elapsed number of seconds
set seconds [expr {$targetTimestamp - $baseTimestamp}]
# 13575721 seconds is a fair while...

Related

Why is MySQL's maximum time limit 838:59:59?

I've run into the limit myself, but despite lots of chatter online, I've never seen an explanation for why the upper and lower limit for the TIME data type is what it is. The official reference at http://dev.mysql.com/doc/refman/5.7/en/time.html says
TIME values may range from '-838:59:59' to '838:59:59'. The hours part may be so large because the TIME type can be used not only to represent a time of day (which must be less than 24 hours), but also elapsed time or a time interval between two events (which may be much greater than 24 hours, or even negative).
But I'm wondering not why the hours part is allowed to be "so large", but why it's cut off where it is. There doesn't seem to be any significance to that many hours in regards to days, or if I try to imagine possible cutoffs for how many seconds could be stored as an integer. So why the range?
The TIME values were always stored on 3 bytes in MySQL. But the format changed on version 5.6.4. I suspect this was not the first time when it changed. But the other change, if there was one, happened long time ago and there is no public evidence of it. The MySQL source code history on GitHub starts with version 5.5 (the oldest commit is from May 2008) but the change I am looking for happened somewhere around 2001-2002 (MySQL 4 was launched in 2003)
The current format, as described in the documentation, uses 6 bits for seconds (possible values: 0 to 63), 6 bits for minutes, 10 bits for hours (possible values: 0 to 1023), 1 bit for sign (add the negative values of the already mentioned intervals) and 1 bit is unused and labelled "reserved for future extensions".
It is optimized for working with time components (hours, minutes, seconds) and doesn't waste much space. Using this format it's possible to store values between -1023:59:59 and +1023:59:59. However MySQL limits the number of hours to 838, probably for backward compatibility with applications that were written a while ago, when I think this was the limit.
Until version 5.6.4, the TIME values were also stored on 3 bytes and the components were packed as days * 24 * 3600 + hours * 3600 + minutes * 60 + seconds. This format was optimized for working with timestamps (because it was, in fact, a timestamp). Using this format it would be possible to store values in the range of about -2330 to +2330 hours. While having this big range of values available, MySQL was still limiting the values to -838 to +838 hours.
There was bug #11655 on MySQL 4. It was possible to return TIME values outside the -838..+838 range using nested SELECT statements. It was not a feature but a bug and it was fixed.
The only reason to limit the values to this range and to actively change any piece of code that produces TIME values outside it was backward compatibility.
I suspect MySQL 3 used a different format that, due to the way the data was packed, limited the valid values to the range -838..+838 hours.
By looking into the current MySQL's source code I found this interesting formula:
#define TIME_MAX_VALUE (TIME_MAX_HOUR*10000 + TIME_MAX_MINUTE*100 + TIME_MAX_SECOND)
Let's ignore for the moment the MAX part of the names used above and let's remember only that TIME_MAX_MINUTE and TIME_MAX_SECOND are numbers between 00 and 59. The formula just concatenates the hours, minutes and seconds in a single integer number. For example, the value 170:29:45 becomes 1702945.
This formula raises the following question: given that the TIME values are stored on 3 bytes with sign, what is the maximum positive value that can be represented this way?
The value we are looking for is 0x7FFFFF that in decimal notation is 8388607. Since the last four digits (8607) should be read as minutes (86) and seconds (07) and their maximum valid values is 59, the greatest value that can be stored on 3 bytes with sign using the formula above is 8385959. Which, as TIME is +838:59:59. Ta-da!
Guess what? The fragment of C code listed above was extracted from this:
/* Limits for the TIME data type */
#define TIME_MAX_HOUR 838
#define TIME_MAX_MINUTE 59
#define TIME_MAX_SECOND 59
#define TIME_MAX_VALUE (TIME_MAX_HOUR*10000 + TIME_MAX_MINUTE*100 + TIME_MAX_SECOND)
I am sure this is how MySQL 3 used to keep the TIME values internally. This format imposed the limitation of the range, and the backward compatibility requirement on the subsequent versions propagated the limitation to our days.
DATETIME is stored based on a base of 10, see Date and Time Data Type Representation:
DATETIME: Eight bytes: A four-byte integer for date packed as YYYY×10000 + MM×100 + DD and a four-byte integer for time packed as HH×10000 + MM×100 + SS
For convinience and some other reasons, the (old) time format was encoded in the same way, using 3 bytes:
Hours * 10000 + Minutes * 100 + Seconds
This means:
3 bytes = 2^24 = 16.777.216
with sign: 2^23 = 8.388.608
Using the encoding, this represents the magical 838 hours. And max. 8608 seconds for the minutes and seconds (without overflow), which results in the largest valid time 838:59:59. One nice thing about this is that the integer representation of that time, 8385959, is easily readable to a human. But this encoding of course leaves gaps, invalid (unused) integer values (like 8309999).
As of MySQL 5.6.4, time format changed its encoding to
1 bit sign (1= non-negative, 0= negative)
1 bit unused (reserved for future extensions)
10 bits hour (0-838)
6 bits minute (0-59)
6 bits second (0-59)
---------------------
24 bits = 3 bytes
Even though it could now store more hours, for compatibility it still just allows 838 hours.
Obviously, it's hard to answer these types of questions without getting direct feedback from the designers of the database.
But there is some documentation regarding how the different data types are stored internally, and, to an extent, it can help us understand this a little bit.
For, instance, regarding the TIME data type, notice how it's stored internally according to the documentation:
TIME encoding for nonfractional part:
1 bit sign (1= non-negative, 0= negative)
1 bit unused (reserved for future extensions)
10 bits hour (0-838)
6 bits minute (0-59)
6 bits second (0-59)
---------------------
24 bits = 3 bytes
So, as you can see, the goal is to fit the information within 3 bytes. And, of those 3 bytes, 10 bits are reserved for the hours, which pretty much determines the overall range.
That said, 10 bits does allow values up to 1023, so I guess, technically, without any changes to the storage size, the range could have been -1023:59:59 to 1023:59:59. Why they didn't do that and they chose 838 as the cutoff, I have no idea.

Date validation with the clock command

Consider the following code run on a Windows 7 system:
% info patchlevel
8.6.4
% clock scan "1995-01-35" -format "%Y-%m-%d"
791856000
% clock format [clock scan "1995-01-35" -format "%Y-%m-%d"] -format "%Y-%m-%d"
1995-02-04
%
I ran into this situation when trying to determine if a string was a valid date, I was expecting the first clock scan to fail as 35 isn't a valid day, but what happens is that I get a date 35 days after the 1st of January.
In my code I'm now comparing the output of the 2nd clock command to the original input and deciding that the string isn't really a valid date if the result is different.
Is there a better way to validate a date and is this the expected behaviour of the clock command, I can't find it described in the manual page for clock?
It is not in-built functionality in Tcl. If the dates/months are exceeding, then it is added to the successive days/months.
In your case, you are giving 35th of month January. The additional 4 days (i.e. 31 + 4 = 35) are added and calculated as month February's 4th day.
In the bizarre case that adding the given number of days yields a date
that does not exist because it falls within the dropped days of the
Julian-to-Gregorian conversion, the date is converted as if it was on
the Julian calendar.
Adding a number of months, or a number of years, is similar; it
converts the given time to a calendar date and time of day. It then
adds the requisite number of months or years, and reconverts the
resulting date and time of day to an absolute time.
If the resulting date is impossible because the month has too few days
(for example, when adding 1 month to 31 January), the last day of the
month is substituted. Thus, adding 1 month to 31 January will result
in 28 February in a common year or 29 February in a leap year.
proc is_valid_date {date {date_format "%Y-%m-%d"}} {
return [string equal [clock format [clock scan $date -format $date_format] -format $date_format] $date]
}
The date format is an optional and defaulted to %Y-%m-%d. If the format is not matching then it will fail. You can handle the exceptions.
Output :
% is_valid_date "1995-02-28"
1
% is_valid_date "1995-01-35"
0
%
We are converting the date to a long and reverting to the date again. If both are not same, then the given input is incorrect.
Reference : clock

getting time in milliseconds from a date

Is it possible to take a string of date, such as 2013-02-26 10:45:54,082 and get the time in milliseconds from the "epoch" ? or something similar?
I know clock scan returns the time in seconds.
Also clock scan returns an error for this specific format.
I couldn't find something as I want, and I want to make sure it doesn't exists before I start creating it...
Thanks
The millisecond-scale offset isn't supported by Tcl (as it is a fairly rare format in practice), but you can work around that:
set str "2013-02-26 10:45:54,082"
regexp {^([^\.,]*)[\.,](\d+)$} $str -> datepart millipart; # split on the last occurrence of , or .
set timestamp [clock scan $datepart -format "%Y-%m-%d %H:%M:%S" -gmt 1]
scan $millipart "%d" millis
set millistamp [expr {$timestamp*1000 + $millis}]
(You don't supply timezone info, so I've assumed it is UTC, i.e., “GMT”. I've also allowed for using . instead of , as a millisecond separator, as which you get depends on the locale that created the time string in the first place.)

How do I optimise displaying time durations in a human-readable way?

I want to implement a functionality for my project. It's very similar to a feature on Stack Overflow where user post requests and gets responses. Here on Stack Overflow we see post marked as 4 seconds ago, 22 seconds ago, 1 minute ago, 5 minutes ago etc. I want to implement the same.
I am storing the request posted time in a timestamp variable in MySQL, then subtracting NOW() - stored_time to get the seconds. Then writing some logic, like
if less than 60 seconds, display 60 seconds ago
if difference in between 60 to 3600, display in minutes
and so on. This long logic is written in Perl. I want to avoid that. Is there any good way to achieve the same thing? I am open to change the MySQL table and data type.
Send number of elapsed seconds to client and convert it to human-readable text in JavaScript.
Retrieve the datestamps as DateTime objects. You don't show any details of your database, so I have to skip that step in my answer.
use DateTime qw();
use DateTime::Format::Human::Duration qw();
for my $seconds (555, 5555, 555555, 5555555) {
my $now = DateTime->now;
my $before = $now->clone->subtract(seconds => $seconds);
my $formatted = DateTime::Format::Human::Duration
->new->format_duration($before - $now);
$formatted =~ s/(?:,| and).*//;
print "about $formatted ago\n";
}
# about 9 minutes ago
# about 1 hour ago
# about 6 days ago
# about 2 months ago

Calculate date from numeric value

The number 71867806 represents the present day, with the smallest unit of days.
Sorry guy's, caching owned me, it's actually milliseconds!
How can I
calculate the currente date from it?
(or) convert it into an Unix timestamp?
Solution shouldn't use language depending features.
Thanks!
This depends on:
What unit this number represents (days, seconds, milliseconds, ticks?)
When the starting date was
In general I would discourage you from trying to reinvent the wheel here, since you will have to handle every single exception in regards to dates yourself.
If it's truly an integer number of days, and the number you've given is for today (April 21, 2010, for me as I'm reading this), then the "zero day" (the epoch) was obviously enough 71867806 days ago. I can't quite imagine why somebody would pick that though -- it works out to roughly 196,763 years ago (~194,753 BC, if you prefer). That seems like a strange enough time to pick that I'm going to guess that there's more to this than what you've told us (perhaps more than you know about).
It seems to me the first thing to do is verify that the number does increase by one every 24 hours. If at all possible keep track of the exact time when it does increment.
First, you have only one point, and that's not quite enough. Get the number for "tomorrow" and see if that's 71867806+1. If it is, then you can safely bet that +1 means +1 day. If it's something like tomorrow-today = 24, then odds are +1 means +1 hour, and the logic to display days only shows you the "day" part. If it's something else check to see if it's near (24*60, which would be minutes), (24*60*60, which would be seconds), or (24*60*60*1000, which would be milliseconds).
Once you have an idea of what kind of units you are using, you can estimate how many years ago the "start" date of 0 was. See if that aligns with any of the common calendar systems located at http://en.wikipedia.org/wiki/List_of_calendars. Odds are that the calendar you are using isn't a truly new creation, but a reimplementation of an existing calendar. If it seems very far back, it might be an Julian Date, which has day 0 equivalent to BCE 4713 January 01 12:00:00.0 UT Monday. Julian Dates and Modified Julian dates are often used in astronomy calculations.
The next major goal is to find Jan 1, 1970 00:00:00. If you can find the number that represents that date, then you simply subtract it from this foreign calendar system and convert the remainder from the discovered units to milliseconds. That will give you UNIX time which you can then use with the standard UNIX utilities to convert to a time in any time zone you like.
In the end, you might not be able to be 100% certain that your conversion is exactly the same as the hand implemented system, but if you can test your assumptions about the calendar by plugging in numbers and seeing if they display as you predicted. Use this technique to create a battery of tests which will help you determine how this system handles leap years, etc. Remember, it might not handle them at all!
What time is: 71,867,806 miliseconds from midnight?
There are:
- 86,400,000 ms/day
- 3,600,000 ms/hour
- 60,000 ms/minute
- 1,000 ms/second
Remove and tally these units until you have the time, as follows:
How many days? None because 71,867,806 is less than 86,400,000
How many hours? Maximum times 3,600,000 can be removed is 19 times
71,867,806 - (3,600,000 * 19) = 3,467,806 ms left.
How many minutes? Maximum times 60,000 can be removed is 57 times.
3,467,806 - (60,000 * 57) = 47,806 ms left
How many seconds? Maximum times 1,000 can be removed is 47 times.
47,806 - (1,000 * 47) = 806
So the time is: 19:57:47.806
It is indeed a fairly long time ago if the smallest number is in days. However, assuming you're sure about it I could suggest the following shell command which would be obviously not valid for dates before 1st Jan. 1970:
date -d "#$(echo '(71867806-71853086)*3600*24'|bc)" +%D
or without bc:
date -d "#$(((71867806 - 71853086) * 3600 * 24))" +%D
Sorry again for the messy question, i got the solution now. In js it looks like that:
var dayZero = new Date(new Date().getTime() - 71867806 * 1000);