Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`DateTime.strptime` returns invalid date for weekday/time string

Why won't Ruby's strptime convert this to a DateTime object:

DateTime.strptime('Monday 10:20:20', '%A %H:%M:%S')
# => ArgumentError: invalid date

While these work?

DateTime.strptime('Wednesday', '%A')
# => #<DateTime: 2015-11-18T00:00:00+00:00 ((2457345j,0s,0n),+0s,2299161j)>
DateTime.strptime('10:20:20', '%H:%M:%S')
# => #<DateTime: 2015-11-18T10:20:20+00:00 ((2457345j,37220s,0n),+0s,2299161j)>
like image 612
Pavel K. Avatar asked Nov 18 '15 16:11

Pavel K.


1 Answers

This looks like a bug - minitech's comment is spot on. For now, though, a workaround (because you probably want this to work now):

You can split it on the space, get the date from the weekday, then get the time component from the other string (using the _strptime method minitech mentioned). Then you can set the time on the first date to the time component from the second string:

def datetime_from_weekday_time_string(string)
  components = string.split(" ")
  date = DateTime.strptime(components[0], '%A')
  time = Date._strptime(components[1], '%H:%M:%S') # returns a hash like {:hour=>10, :min=>20, :sec=>20} 
  return date.change(time)
end

2.2.2 :021 > datetime_from_weekday_time_string("Monday 10:20:20")
 => Mon, 16 Nov 2015 10:20:20 +0000 

2.2.2 :022 > datetime_from_weekday_time_string("Saturday 11:45:21")
 => Sat, 21 Nov 2015 11:45:21 +0000

2.2.2 :023 > datetime_from_weekday_time_string("Thursday 23:59:59")
 => Thu, 19 Nov 2015 23:59:59 +0000 
like image 76
Undo Avatar answered Sep 30 '22 15:09

Undo