Time and Date Stamps
Author: Carl Sassenrath
This example shows some simple ways to create and save timestamps. This is useful if you need to keep track when an event occurred, such as the last time you downloaded a file from a server, or the last time you checked a website, etc. I also show how to create coded timestamps, such as those used for filenames.
Here is how to get the current date and time (with timezone) and save it to a file:
To load the timestamp back later:
Here's a complete program that keeps a datestamp each time you run it:
You can create coded timestamps such as those used for creating unique filenames based on time. For example, sometimes you need to create filenames that have the form:
Where YYYY is year , MM is month, DD is day, etc. (It is done in this order so files names appear in chronological order in directories.)
Here's a function that will return a date and time coded string:
Here's what the result will look like:
Now you can create a filename based on a date and time:
I often use a variation on this function that will create a smaller filename by using letters as well as numbers (think of it as base-36 encoding, 10 numbers and 26 letters).
Note: this timestamp is only accurate to within two minutes. If you need greater accuracy, you will need to make minutes and seconds two digits (as in prior example). Do not try to extend the base string to 60 by adding uppercase characters, because not all operating systems distinguish upper and lower case in filenames.
The resulting string is now only five letters long:
You can use the new function as you did before: