Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What am I doing wrong with DateTime.strptime?

Tags:

datetime

ruby

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 this:

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>'
like image 508
0x26res Avatar asked Mar 21 '11 16:03

0x26res


People also ask

What does DateTime DateTime Strptime do?

Python DateTime – strptime() Function strptime() is another method available in DateTime which is used to format the time stamp which is in string format to date-time object.

What does DateTime Strptime return?

Python time strptime() function The strptime() function in Python is used to format and return a string representation of date and time. It takes in the date, time, or both as an input, and parses it according to the directives given to it.

What does Strptime mean?

The strptime() function converts the character string pointed to by buf to values which are stored in the tm structure pointed to by tm, using the format specified by format. The format is composed of zero or more directives.

Which two parameters does the DateTime Strptime () function requires?

The strptime() class method takes two arguments: string (that be converted to datetime) format code.


1 Answers

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

like image 85
michaelmichael Avatar answered Oct 08 '22 18:10

michaelmichael