开发者

What am I doing wrong with DateTime.strptime?

My ruby program says that my date is invalid when I do that:

format = "%D/%M/%Y %H:%M:%S:3N"
date = "21/03/2011 16:39:11.642"

DateTime.strptime(time, format)

I have also tried this one:

format = "%D/%M/%Y %H:%M:%S:3"

All I get is th开发者_如何学Pythonis:

ArgumentError: invalid date    
        from /usr/local/lib/ruby/1.9.1/date.rb:1688:in `new_by_frags'    
        from /usr/local/lib/ruby/1.9.1/date.rb:1713:in `strptime'
        from (irb):12  
        from /usr/local/bin/irb:12:in `<main>'


It looks like you were getting strptime's format directives confused. Notice how %M is in format twice, once representing the month and the next time representing the minute?

%D means the date as %m / %d / %y.

%d means the day of the month [01,31]

%M means the minute [00,59]

%m means the month number [01,12]

This should work:

format = "%d/%m/%Y %H:%M:%S"
date_time = "21/03/2011 16:39:11.642"

puts DateTime.strptime(date_time, format) #=> 2011-03-21T16:39:11+00:00

Here's a strptime reference


Try to use

datetime.to_date.strftime(format)

or

datetime.to_time

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜