On 26 Oct 2007, at 13:03, John Carter wrote:

> Hmm. Ooh yuck.
>
> Try this...
>
> $ ruby -r time -e 'a=Time.now;p a-Time.parse(a.to_s)'
> 0.00848
> $ ruby -r time -e 'a=Time.now;p a-Time.parse(a.to_s)'
> 0.446575
> $ ruby -r time -e 'a=Time.now;p a-Time.parse(a.to_s)'
> 0.142796
>
> ie. Time#to_s doesn't represent the full precision of the internal
> time format.
>
> Bit of a bummer if you want to round trip an exact timestamp onto disk
> and back.
>
> This does it right...
> $ ruby -e 'a=Time.now;p a-Marshal::load(Marshal::dump(a))'
> 0.0
>
>
> ...but look at whats on disk...
> ruby -e 'a=Time.now;p Marshal::dump(a)'
> "\004\bu:\tTime\rC\347\032\200z\343S\302"
>
> Eeew! Not exactly human friendly.
>
> The following is probably the most elegant way of exactly round
> tripping a time to disk and back in a human readable form?
>
> ruby -w -rtime -e 'a=Time.now;b = a.xmlschema(6);p b;p a- 
> Time.xmlschema(b)'
> "2007-10-26T17:01:08.129059+13:00"
> 0.0

You can use YAML if you only want Time.

irb(main):002:0> Time.now.to_yaml
=> "--- 2007-10-26 13:10:45.012414 +09:00\n"
irb(main):003:0> YAML.load(Time.now.to_yaml)
=> Fri Oct 26 13:10:55 +0900 2007

irb(main):004:0> t = Time.now
=> Fri Oct 26 13:13:05 +0900 2007
irb(main):005:0> t - YAML.load(t.to_yaml)
=> 0.0

Though there's a bug with DateTime:

irb(main):006:0> DateTime.now.to_yaml
=> "--- !timestamp 2007-10-26T13:11:15+0900\n"
irb(main):007:0> YAML.load(DateTime.now.to_yaml)
=> Wed Sep 19 10:11:26 +0900 2007

Alex Gutteridge

Bioinformatics Center
Kyoto University