Tag Archives: programming

date crap

How to get the current epoch time in …

Perl time
PHP time()
Ruby Time.now (or Time.new). To display the epoch: Time.now.to_i
Python import time first, then time.time()
Java long epoch = System.currentTimeMillis()/1000;
Microsoft .NET C# epoch = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
VBScript/ASP DateDiff("s", "01/01/1970 00:00:00", Now())
Erlang calendar:datetime_to_gregorian_seconds(calendar:now_to_universal_time( now()))-719528*24*3600.
MySQL SELECT unix_timestamp(now()) More information
PostgreSQL SELECT extract(epoch FROM now());
Oracle PL/SQL SELECT (SYSDATE - TO_DATE('01-01-1970 00:00:00', 'DD-MM-YYYY HH24:MI:SS')) *
24 * 60 * 60 FROM DUAL
SQL Server SELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE())
JavaScript Math.round(new Date().getTime()/1000.0) getTime() returns time in milliseconds.
Unix/Linux date +%s
PowerShell Get-Date -UFormat "%s" Produces: 1279152364.63599
Other OS’s Command line: perl -e "print time" (If Perl is installed on your system)

Convert from human readable date to epoch

Perl Use these Perl Epoch routines
PHP mktime(hour, minute, second, month, day, year) More information
Ruby Time.local(year, month, day, hour, minute, second, usec ) (or Time.gm for GMT/UTC input). To display add .to_i
Python import time first, then int(time.mktime(time.strptime('2000-01-01 12:34:00', '%Y-%m-%d %H:%M:%S'))) - time.timezone
Java long epoch = new java.text.SimpleDateFormat ("dd/MM/yyyy HH:mm:ss").parse("01/01/1970 01:00:00");
VBScript/ASP DateDiff("s", "01/01/1970 00:00:00", time field) More information
MySQL SELECT unix_timestamp(time) Time format: YYYY-MM-DD HH:MM:SS or YYMMDD or YYYYMMDD
More on using Epoch timestamps with MySQL
PostgreSQL SELECT extract(epoch FROM date('2000-01-01 12:34'));
With timestamp: SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40-08');
With interval: SELECT EXTRACT(EPOCH FROM INTERVAL '5 days 3 hours');
SQL Server SELECT DATEDIFF(s, '1970-01-01 00:00:00', time field)
JavaScript use the JavaScript Date object
Unix/Linux date +%s -d"Jan 1, 1980 00:00:01" Replace ‘-d’ with ‘-ud’ to input in GMT/UTC time.

Convert from epoch to human readable date

Perl Use these Perl Epoch routines
PHP date(output format, epoch); Output format example: ‘r’ = RFC 2822 date More information
Ruby Time.at(epoch)
Python import time first, then time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(epoch)) Replace time.localtime with time.gmtime for GMT time. More information
Java String date = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000));
VBScript/ASP DateAdd("s", epoch, "01/01/1970 00:00:00") More information
MySQL from_unixtime(epoch, optional output format) The default output format is YYY-MM-DD HH:MM:SS more …
PostgreSQL PostgreSQL version 8.1 and higher: SELECT to_timestamp(epoch); More information Older versions: SELECT TIMESTAMP WITH TIME ZONE 'epoch' + epoch * INTERVAL '1 second';
SQL Server DATEADD(s, epoch, '1970-01-01 00:00:00')
Microsoft Excel =(A1 / 86400) + 25569 Format the result cell for date/time, the result will be in GMT time (A1 is the cell with the epoch number). For other timezones: =((A1 +/- timezone adjustment) / 86400) + 25569.
Crystal Reports DateAdd("s", {EpochTimeStampField}-14400, #1/1/1970 00:00:00#) -14400 used for Eastern Standard Time. See Timezones.
JavaScript use the JavaScript Date object
Unix/Linux date -d @1190000000 Replace 1190000000 with your epoch, needs recent version of ‘date’. Replace ‘-d’ with ‘-ud’ for GMT/UTC time.
PowerShell Function get-epochDate ($epochDate) { [timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($epochDate)) }, then use: get-epochDate 1279152364. Works for Windows PowerShell v1 and v2
Other OS’s Command line: perl -e "print scalar(localtime(epoch))" (If Perl is installed) Replace ‘localtime’ with ‘gmtime’ for GMT/UTC time.

create graphviz image from textfile

inspired by text2mindmap.com i decided to create something similar in python.

Here’s the result:

Code text2mindmap.py

import pydot
import sys
def ReadFile(filename):
  fh = open(filename)
  return [x.rstrip() for x in fh.readlines()]
def CreateEdges(lines):
  edge_list= ['' for x in range(100)]
  edges = []
  for line in lines:
    pos = line.count('\t');
    edge_list[pos] = line.replace('\t', '')
    if pos:
      edges.append((edge_list[pos -1], edge_list[pos]))
  return edges
def CreateGraphFromEdges(edges, output):
  g=pydot.graph_from_edges(edges, directed=True)
  return g.write_png('%s.png' % output, prog='dot')    
def main(argv):
  CreateGraphFromEdges(CreateEdges(ReadFile(argv[1])), argv[2])
if __name__ == "__main__":

Source file months.txt

Months of the year

How to generate the image:

$ ./text2mindmap.py months.txt months

pydot + graphviz

Install pydot
Install graphviz

$ python
Python 2.5.1 (r251:54863, Feb  9 2009, 18:49:36) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pydot
>>> edges=[('1','2'), ('1','3'), ('1','4'), ('3','4')]
>>> g=pydot.graph_from_edges(edges)
>>> g.write_jpeg('graph_from_edges_dot.jpg', prog='dot')


C enums

#include <stdio .h>
enum months {
const char *monthName[] = { "", "January", "February", "March",   
"April", "May", "June", "July", "August", "September", "October",
"November", "December" };
int main() {
enum months month;  
for (month = JAN; month < = DEC; month++) {
return 0;

C pointers

* Once a variable is declared, we can get its address by preceding its name with the unary & operator, as in &k.
* We can “dereference” a pointer, i.e. refer to the value of that which it points to, by using the unary ‘*’ operator as in *ptr.
* An “lvalue” of a variable is the value of its address, i.e. where it is stored in memory.
The “rvalue” of a variable is the value stored in that variable (at that address).

#include <stdio .h>
int main()
int k=3;
int *ptr;
ptr = &k;
printf("The value ptr is pointing to:%d at address:%p\n", *ptr, ptr);

C prinft formatting

Where specifier is the most significant one and defines the type and the interpretation of the value of the coresponding argument:

specifier Output Example
c Character a
d or i Signed decimal integer 392
e Scientific notation (mantise/exponent) using e character 3.9265e+2
E Scientific notation (mantise/exponent) using E character 3.9265E+2
f Decimal floating point 392.65
g Use the shorter of %e or %f 392.65
G Use the shorter of %E or %f 392.65
o Signed octal 610
s String of characters sample
u Unsigned decimal integer 7235
x Unsigned hexadecimal integer 7fa
X Unsigned hexadecimal integer (capital letters) 7FA
p Pointer address B800:0000
n Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored.
% A % followed by another % character will write % to stdout.

Strings in C

C doesn’t know about strings. It knows about characters, and thus, a string is an array of characters like so:

char the_string[] = "this is my fancy string";

Another way to allocate a number of chars is this:

char the_string[50];

To show that its really an array:

#include <stdio .h>
int main() {
  char some_array[] = {'a', 'b', 'c'};
  printf("%s\n", some_array);
  return 0;

Which yields:


Here we create an array of characters named the_string. A string in C is terminated by the “\0″ (NULL) character.

Example of passing a string to a method called print:

#include <stdio .h>
void print(char string[]) {
  printf("%s\n", string);
int main() {
  print("test 1 2 3");
  return 0;