I'm attempting to use boost::date_time to parse a date string (obtained from the Twitter API) into a ptime object. An example of the date format is:
Thu Mar 24 16:12:42 +0000 2011
No matter what I do though, I get a "Year is out of valid range" exception while trying to parse the string. The date format looks correct to me, here is the code:
boost::posix_time::ptime created_time;
std::stringstream ss(created_string);
ss.exceptions(std::ios_base::failbit); //Turn on exceptions
ss.imbue(std::locale(ss.getloc(), new boost::posix_time::time_input_facet("%a %b %d %T %q %Y")));
ss >> created_time;
In the above code "created_string" contains the above date. Have I made a mistake in the format string?
The fromtimestamp() function is used to return the date corresponding to a specified timestamp. Note: Here the timestamp is ranging from the year 1970 to the year 2038, and this function does not consider leap seconds if any present in the timestamp. This function is a class method.
YYYY-MM-DD You can convert datetime objects and pandas Timestamp object to string with str or the strftime method: %Y means four-digit year, %m presents two-digit month, %d describes two-digit day, %F is the shortcut for %Y-%m-%d .
Both %T
and %q
are output-online format flags.
To demonstrate that, change your format to "%a %b %d %H:%M:%S +0000 %Y"
and your program will run as described.
As for time zone input, it is a bit more complex, you may have to pre-process the string to change +0000 to posix time zone format first.
EDIT: for example you could do it this way:
#include <iostream>
#include <sstream>
#include <boost/date_time.hpp>
int main()
{
//std::string created_string = "Thu Mar 24 16:12:42 +0000 2011";
// write your own function to search and replace +0000 with GMT+00:00
std::string created_string = "Thu Mar 24 16:12:42 GMT+00:00 2011";
boost::local_time::local_date_time created_time(boost::local_time::not_a_date_time);
std::stringstream ss(created_string);
ss.exceptions(std::ios_base::failbit);
ss.imbue(std::locale(ss.getloc(),
new boost::local_time::local_time_input_facet("%a %b %d %H:%M:%S %ZP %Y")));
ss >> created_time;
std::cout << created_time << '\n';
}
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