Reputation: 1222
Can someone verify my datetime conversion error.
What I have is a hash of days of the week as number fixnum keys generated from the Date library. I sorted the hash and I want to convert the fixnum keys to days of the week (ie 0 --> Sunday)
My hash output is {3=>7, 2=>1, 4=>2}
( using dh=Hash[dh.sort]
I would get {2=>1, 3=>7, 4=>2}
)
after the sort, I try to perform a .each do
dh = {3=>7, 2=>1, 4=>2}
dh=Hash[dh.sort]
dh.each do |day,reg|
#puts day.class
#puts day="3" # This works
day=day.to_s ##<<== problem here: error "invalid date" when evaluated by strptime
## if don't do day.to_s conversion, error "can't convert fixnum into string"
#day="#{day}" ## does not work either
wday= DateTime.strptime(day,'%d') ##<<== and problem here
puts wday.strftime("%a")
puts wday
end
so the day
variable is a fixnum. So no matter what I do to the day variable (convert to string, or leave it as fixnum), the strptime does not work.
It does not matter if I make up another variable such as xyz = day.to_s
, the xyz
variable would still get error out by the strptime method.
But if I manually assign the day variable a string value day="3"
, then the strptime would work.
Any insight into this problem, is this a bug?
Upvotes: 0
Views: 452
Reputation: 1222
Editted to reflect the correct cause pointed out.
OK, I figured out the problem
I originally used the
datestamp = DateTime.strptime(datestr, '%m/%d/%y %H:%M')
and the datestamp.wday
to create a hash with #wday values as the keys. These #wday values are numbers from 0-6 to represent Sunday-Saturday.
When I used the DateTime.strptime(day,'%d')
, I should had used the %w switch. The correct statement should have been DateTime.strptime(day.to_s,'%w')
Upvotes: 0
Reputation: 7719
If I do understand you correctly, you are confusing the proper datetime format. If you need to handle the weekday number you need to put %w
instead of %d
ie. day of the month.
dh = {3=>7, 2=>1, 4=>2, 0=>5}.sort
dh.each do |day,reg|
day=day.to_s
wday= DateTime.strptime(day,'%w')
puts wday.strftime("%a")
end
# Sun
# Tue
# Wed
# Thu
Upvotes: 1
Reputation: 44370
This work
=> dh = {3=>2, 2=>7}
=> {3=>2, 2=>7}
=> dh = Hash[dh.sort]
=> {2=>7, 3=>2}
=> dh.each { |day,reg| DateTime.strptime(day,'%d') }
=> TypeError: no implicit conversion of Fixnum into String
=> dh.each { |day,reg| puts DateTime.strptime(day.to_s,'%d') }
=> 2013-12-02T00:00:00+00:00
=> 2013-12-03T00:00:00+00:00
=> {2=>7, 3=>2}
Upvotes: 0