From: "Ara.T.Howard" Date: 2004-04-02T00:14:33+09:00 Subject: Re: How to get internal state of DateTime in seconds On 1 Apr 2004, G'irts Kalnins wrote: > > >How do you get internal state in seconds of DateTime instance? > > >Or convert it to Time instance? > > > > > >I want to compare two times with variable precision. > > >Below is my try to parse time from Common Log Format. > > > > > >require 'date' > > >str1 = '20/Nov/2003:08:08:09 +0200' > > >str2 = '20/Nov/2003:08:04:09 +0200' > > >fmt='%d/%b/%Y:%H:%M:%S %Z' > > >t1 = DateTime.strptime(str1, fmt) > > >t2 = DateTime.strptime(str2, fmt) > > > > > >#what is difference in minutes between these 2 times? > > > Use to_i if you want it as an integer number of seconds > > > > $ ruby -we 'puts Time.now.to_i' > > => 1080754316 > > There is no DateTime#to_i > Right now I do like below and it looks ugly to me. > > def dateToTime(str) > d = DateTime.strptime(str, fmt='%d/%b/%Y:%H:%M:%S %Z') > t = Time.local(d.year, d.month, d.day, d.hour, d.min, d.sec) > t > end iff - your times are a common format - your times are within the ranges allowable by Time both of which appear to be true why not simply parse the time yourself? this is plenty clean, especially if it's in instance method of a LogEntry class or something: file: logtm.rb def logtm s #{{{ pat = %r|^\s*(\d\d)/(\w\w\w)/(\d\d\d\d):(\d\d):(\d\d):(\d\d)\s+\+(\d\d)(\d\d)\s*$|io s = s.to_s m = pat.match s raise ArgumentError, "<#{ s.inspect }>" unless m parts = m.to_a raise ArgumentError, "<#{ s.inspect }>" unless parts.size == 9 parts.shift day, month, year, hour, min, sec, zhour, zmin = parts months = %w(jan feb mar apr may jun jul aug sep oct nov dec) i = months.index month.downcase raise ArgumentError, "<#{ s.inspect }>" unless i month = i + 1 day, month, year, hour, min, sec, zhour, zmin = [day, month, year, hour, min, sec, zhour, zmin].map{|x| x.to_i} utc = Time.utc year, month, day, hour, min, sec, usec = 0 t = utc + ((zhour * 60 * 60) + (zmin * 60)) #}}} end str1 = '20/Nov/2003:08:08:09 +0200' str2 = '20/Nov/2003:08:04:09 +0200' t1 = logtm str1 t2 = logtm str2 #what is difference in minutes between these 2 times? p((t1 - t2).abs / 60.0) # => 4.0 -a -- =============================================================================== | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov | PHONE :: 303.497.6469 | ADDRESS :: E/GC2 325 Broadway, Boulder, CO 80305-3328 | URL :: http://www.ngdc.noaa.gov/stp/ | TRY :: for l in ruby perl;do $l -e "print \"\x3a\x2d\x29\x0a\"";done ===============================================================================