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>'
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.
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.
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.
The strptime() class method takes two arguments: string (that be converted to datetime) format code.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With