gpt4 book ai didi

c++ - boost::posix_time::time_input_facet 可以处理非标准的小数秒分隔符吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:16:33 25 4
gpt4 key购买 nike

我正在尝试从文本文件中解析日期时间。时间戳具有微秒精度,但由于我无法控制的历史原因,它们是使用冒号而不是点来分隔小数秒部分创建的,例如:

2015/05/05 03:10:43:537408

代替

2015/05/05 03:10:43.537408

我能够使用以下代码解析这些时间戳而不保留小数秒:

#include <iostream>
#include <sstream>
#include <boost/date_time.hpp>
namespace bt = boost::posix_time;

const std::string inputString = "2015/05/05 03:10:43:537408";
const std::string inputFormat = "%Y/%m/%d %H:%M:%S%F";

bt::time_input_facet * facet = new bt::time_input_facet(inputFormat);
const std::locale loc(std::locale::classic(), facet);

std::istringstream iss(inputString);
iss.imbue(loc);
boost::posix_time::ptime pt;
iss >> pt;

您可能会猜到,使用小写-f 小数秒格式化程序会导致解析失败(pt 仍然不是日期时间)。此外,在格式字符串中插入冒号也无济于事:

const std::string inputFormat = "%Y/%m/%d %H:%M:%S:%F";

Boost 似乎可以推断点分隔符。

除了显式检查冒号分隔符并以不同方式处理它之外,有谁知道是否可以使用 boost 库解析这种非标准时间格式?

最佳答案

没有内置方法。

time_facet get 函数假定 '.' 作为分隔符:

    case 'f':
{
// check for decimal, check SV if missing
if(*sitr == '.') {
++sitr;
parse_frac_type(sitr, stream_end, frac);
// sitr will point to next expected char after this parsing
// is complete so no need to advance it
use_current_char = true;
}
else {
return check_special_value(sitr, stream_end, t, c);
}
break;
}
case 'F':
{
// check for decimal, skip if missing
if(*sitr == '.') {
++sitr;
parse_frac_type(sitr, stream_end, frac);
// sitr will point to next expected char after this parsing
// is complete so no need to advance it
use_current_char = true;
}
else {
// nothing was parsed so we don't want to advance sitr
use_current_char = true;
}
break;
}

您可以修改实现(参见例如 Format a posix time with just 3 digits in fractional seconds )或子类化并覆盖相关的成员函数。

无论如何都会有点烦人,因为该类不是为继承而设计的。

我个人会想到一个格式字符串来指示只是小数设置没有任何分隔符,所以你确实可以在格式规范。

关于c++ - boost::posix_time::time_input_facet 可以处理非标准的小数秒分隔符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32059946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com