unix timestamp to boost::posix_time::ptime

2019-02-21 13:45发布

I need to convert double with number of seconds since the epoch to ptime. I'm prety sure there must be an easy way to do this, but I couldn't find anything. Thanks.

Edit: The original timestamp is floating point. I can't change it and i don't want to lose the sub-second precision.

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-02-21 14:08

For a machine that has boost date/time compiled to the default level of microsecond resolution, try this:

double ts = 1250524800.5;
// Use floor() here if seconds are always positive.
time_t secondsSinceEpoch = floor(ts);
long microsecondsSinceSecond =
    floor((ts - static_cast<double>(secondsSinceEpoch)) * 1000000);
boost::posix_time::ptime result =
    boost::posix_time::from_time_t(secondsSinceEpoch);
boost::posix_time::time_duration fractionalSeconds(0, 0, 0,
                                                   microsecondsSinceSecond);
result += fractionalSeconds;
cout << "Time stamp is " << result << endl;

The output for this is "Time stamp is 2009-Aug-17 16:00:00.500000" on my linux box.

查看更多
欢心
3楼-- · 2019-02-21 14:08

after some fiddling around i came up with this:

ptime(date(1970, 1, 1), time_duration(0, 0, 0, time_duration::ticks_per_second() * 1234567890.0987654321))

I'm not sure this is the best solution, but it seems to do what i need.

查看更多
再贱就再见
4楼-- · 2019-02-21 14:27

Use the from_time_t() conversion function. A time_t is a UNIX timestamp, i.e. the number of seconds since the epoch.

查看更多
登录 后发表回答