我有一个从Daunt Books抓取的字符串:
"Monday 2 December 6.30pm"
但是我似乎无法使用DateTime#strptime
将其转换为DateTime。日期部分似乎起作用:
(byebug) DateTime.strptime(str,"%A %d %B")
#<DateTime: 2019-12-02T00:00:00+00:00 ((2458820j,0s,0n),+0s,2299161j)>
但是时间返回错误:
(byebug) DateTime.strptime(str,"%A %d %B %l.%M%P")
*** ArgumentError Exception: invalid date
nil
我知道这是正确的#strptime
代码,因为如果未从网页上将其抓取,它将在字符串上起作用。我无法解决使字符串对#strptime
有效的问题。
可能是编码问题?
点是非标准的,请替换它:
DateTime.strptime(str.gsub('.',':'),"%A %d %B %l:%M%P")
=>Mon, 02 Dec 2019 18:30:00 +0000
我无法复制问题:
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)>
这对我有用:
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"
和:
DateTime.strptime(foo, '%a %d %B %l.%M%p').strftime('%A %e %B %l:%M%p')
# => "Monday 2 December 6:30PM"