How to parse a date? (strptime problem)

G

gabriele renzi

Hi gurus and nubys,
I was wondering how to parse a line like this:
01/Oct/1980:01:56:57

I know I can use strftime() to write it:=> "10/Oct/2003:10:16:29"

And I supposed I could use DateTime.strptime() to parse it
(strptime() seem to get a format argument).
But if I try:ArgumentError: invalid date

How should I parse a line using a self-defined format?
 
O

Ollivier Robert

How should I parse a line using a self-defined format?

Here is what I do:

-=-=-
def process_entry (entry)
# Get the ASCII date
#
c_date = entry[-1].sub(/^Canceled on: (.*)$/, '\1')

# Get a hash from the string
#
h_date = Date::strptime(c_date, "%d %b %Y %T %Z")

# Get a Time object
#
n_date = Time.gm(h_date[:year], h_date[:mon], h_date[:mday],
h_date[:hour], h_date[:min], h_date[:sec])

# Check whether we keep the record or not (i.e. older than $num_days)
#
if n_date < ($now - $num_days * SPERDAY)
return true
else
return false
end
end

private :process_entry
-=-=-

Dates are like this:

Canceled on: 21 Mar 2002 21:27:01 GMT
 
T

ts

g> => "10/Oct/2003:10:16:29"
^^
^^

Well, try these 2 commands

DateTime.now.to_s
DateTime.now.strftime("%m/%b/%Y:%H:%M:%S")

You don't think that it exist a problem ?

g> And I supposed I could use DateTime.strptime() to parse it
g> (strptime() seem to get a format argument).
g> But if I try:g> ArgumentError: invalid date

Your format is wrong, you must use %d (day) rather than %m (month)

svg% irb
irb(main):001:0> require 'date'
=> true
irb(main):002:0> fmt= "%d/%b/%Y:%H:%M:%S"
=> "%d/%b/%Y:%H:%M:%S"
irb(main):003:0> z = DateTime.now.strftime(fmt)
=> "23/Oct/2003:14:36:15"
irb(main):004:0> DateTime.strptime z,fmt
=> #<DateTime: 2825782397/1152,0,2299161>
irb(main):005:0>
svg%
 
G

gabriele renzi

il 23 Oct 2003 14:39:11 +0200 said:
g> And I supposed I could use DateTime.strptime() to parse it
g> (strptime() seem to get a format argument).
g> But if I try:
g> ArgumentError: invalid date

Your format is wrong, you must use %d (day) rather than %m (month)


oops... thanks for the answers
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,138
Messages
2,570,804
Members
47,349
Latest member
jojonoy597

Latest Threads

Top