Reputation: 408
I have a string which is scraped from Daunt Books:
"Monday 2 December 6.30pm"
but I can't seem to convert it to a DateTime with DateTime#strptime
. The date part seems to work:
(byebug) DateTime.strptime(str,"%A %d %B")
#<DateTime: 2019-12-02T00:00:00+00:00 ((2458820j,0s,0n),+0s,2299161j)>
but the time returns an error:
(byebug) DateTime.strptime(str,"%A %d %B %l.%M%P")
*** ArgumentError Exception: invalid date
nil
I know this is the correct #strptime
code because it works on the string if it is not scraped from the web page. I can't work out what I need to do to make the string valid for #strptime
to work.
EDIT:
Unfortunately the website I was scraping from was redesigned the day after the OP and the scraping code is now defunkt.
Upvotes: 1
Views: 424
Reputation: 160571
I can't duplicate the problem:
require 'date'
str = "Monday 2 December 6.30pm"
DateTime.strptime(str,"%A %d %B %l.%M%P")
# => #<DateTime: 2019-12-02T18:30:00+00:00 ((2458820j,66600s,0n),+0s,2299161j)>
And this works for me:
require 'date'
foo = "Monday 2 December 6.30pm"
bar = DateTime.strptime(foo, '%a %d %B %l.%M%p')
bar.to_s
# => "2019-12-02T18:30:00+00:00"
and:
DateTime.strptime(foo, '%a %d %B %l.%M%p').strftime('%A %e %B %l:%M%p')
# => "Monday 2 December 6:30PM"
Upvotes: 2