如何将std :: chrono :: time_point转换为带有小数秒的日历日期时间字符串?

时间:2012-10-11 08:43:52

标签: c++ datetime c++11 std chrono

如何使用小数秒将std :: chrono :: time_point转换为日历日期时间字符串? 例如:“10-10-2012 12:38:40.123456”。

7 个答案:

答案 0 :(得分:55)

如果是system_clock,则此类具有time_t转换。

#include <iostream>
#include <chrono>
#include <ctime>

using namespace std::chrono;

int main()
{
  system_clock::time_point p = system_clock::now();

  std::time_t t = system_clock::to_time_t(p);
  std::cout << std::ctime(&t) << std::endl; // for example : Tue Sep 27 14:21:13 2011
}

示例结果:

Thu Oct 11 19:10:24 2012

编辑: 但是,time_t不包含小数秒。 另一种方法是使用time_point :: time_since_epoch()函数。此函数从epoch返回持续时间。 以下示例是毫秒秒分辨率的小数。

#include <iostream>
#include <chrono>
#include <ctime>

using namespace std::chrono;

int main()
{
  high_resolution_clock::time_point p = high_resolution_clock::now();

  milliseconds ms = duration_cast<milliseconds>(p.time_since_epoch());

  seconds s = duration_cast<seconds>(ms);
  std::time_t t = s.count();
  std::size_t fractional_seconds = ms.count() % 1000;

  std::cout << std::ctime(&t) << std::endl;
  std::cout << fractional_seconds << std::endl;
}

示例结果:

Thu Oct 11 19:10:24 2012

925

答案 1 :(得分:29)

首先创建一个对应于10-10-2012 12:38:40的std::tm的自解释代码,将其转换为std::chrono::system_clock::time_point,添加0.123456秒,然后将其打印出来转换回std::tm。如何处理小数秒是最后一步。

#include <iostream>
#include <chrono>
#include <ctime>

int main()
{
    // Create 10-10-2012 12:38:40 UTC as a std::tm
    std::tm tm = {0};
    tm.tm_sec = 40;
    tm.tm_min = 38;
    tm.tm_hour = 12;
    tm.tm_mday = 10;
    tm.tm_mon = 9;
    tm.tm_year = 112;
    tm.tm_isdst = -1;
    // Convert std::tm to std::time_t (popular extension)
    std::time_t tt = timegm(&tm);
    // Convert std::time_t to std::chrono::system_clock::time_point
    std::chrono::system_clock::time_point tp = 
                                     std::chrono::system_clock::from_time_t(tt);
    // Add 0.123456 seconds
    // This will not compile if std::chrono::system_clock::time_point has
    //   courser resolution than microseconds
    tp += std::chrono::microseconds(123456);

    // Now output tp

    // Convert std::chrono::system_clock::time_point to std::time_t
    tt = std::chrono::system_clock::to_time_t(tp);
    // Convert std::time_t to std::tm (popular extension)
    tm = std::tm{0};
    gmtime_r(&tt, &tm);
    // Output month
    std::cout << tm.tm_mon + 1 << '-';
    // Output day
    std::cout << tm.tm_mday << '-';
    // Output year
    std::cout << tm.tm_year+1900 << ' ';
    // Output hour
    if (tm.tm_hour <= 9)
        std::cout << '0';
    std::cout << tm.tm_hour << ':';
    // Output minute
    if (tm.tm_min <= 9)
        std::cout << '0';
    std::cout << tm.tm_min << ':';
    // Output seconds with fraction
    //   This is the heart of the question/answer.
    //   First create a double-based second
    std::chrono::duration<double> sec = tp - 
                                    std::chrono::system_clock::from_time_t(tt) +
                                    std::chrono::seconds(tm.tm_sec);
    //   Then print out that double using whatever format you prefer.
    if (sec.count() < 10)
        std::cout << '0';
    std::cout << std::fixed << sec.count() << '\n';
}

对我来说这是输出:

10-10-2012 12:38:40.123456

您的std::chrono::system_clock::time_point可能或可能不够精确,无法保持微秒。

<强>更新

更简单的方法是使用this date library。代码简化为(使用C ++ 14持续时间文字):

#include "date.h"
#include <iostream>
#include <type_traits>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    auto t = sys_days{10_d/10/2012} + 12h + 38min + 40s + 123456us;
    static_assert(std::is_same<decltype(t),
                               time_point<system_clock, microseconds>>{}, "");
    std::cout << t << '\n';
}

输出:

2012-10-10 12:38:40.123456

如果您不需要证明static_assert的类型是t,则可以跳过std::chrono::time_point

如果输出不符合您的喜好,例如您真的喜欢dd-mm-yyyy订购,您可以:

#include "date.h"
#include <iomanip>
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    using namespace std;
    auto t = sys_days{10_d/10/2012} + 12h + 38min + 40s + 123456us;
    auto dp = floor<days>(t);
    auto time = make_time(t-dp);
    auto ymd = year_month_day{dp};
    cout.fill('0');
    cout << ymd.day() << '-' << setw(2) << static_cast<unsigned>(ymd.month())
         << '-' << ymd.year() << ' ' << time << '\n';
}

完全给出了请求的输出:

10-10-2012 12:38:40.123456

<强>更新

以下是如何以毫秒精度整齐地格式化当前时间UTC:

#include "date.h"
#include <iostream>

int
main()
{
    using namespace std::chrono;
    std::cout << date::format("%F %T\n", time_point_cast<milliseconds>(system_clock::now()));
}

只为我输出:

2016-10-17 16:36:02.975

C ++ 17允许您将time_point_cast<milliseconds>替换为floor<milliseconds>。在此之前,date::floor中提供了"date.h"

std::cout << date::format("%F %T\n", date::floor<milliseconds>(system_clock::now()));

答案 2 :(得分:7)

一般来说,你不能以任何直截了当的方式做到这一点。 time_point基本上只是时钟特定时期的duration

如果您有std::chrono::system_clock::time_point,则可以使用std::chrono::system_clock::to_time_ttime_point转换为time_t,然后使用正常的C函数,例如{{1}或ctime格式化它。


示例代码:

strftime

答案 3 :(得分:3)

这适用于我的格式,如YYYY.MM.DD-HH.MM.SS.fff。尝试使这段代码能够接受任何字符串格式就像重新发明轮子一样(即Boost中有所有这些功能。

std::chrono::system_clock::time_point string_to_time_point(const std::string &str)
{
    using namespace std;
    using namespace std::chrono;

    int yyyy, mm, dd, HH, MM, SS, fff;

    char scanf_format[] = "%4d.%2d.%2d-%2d.%2d.%2d.%3d";

    sscanf(str.c_str(), scanf_format, &yyyy, &mm, &dd, &HH, &MM, &SS, &fff);

    tm ttm = tm();
    ttm.tm_year = yyyy - 1900; // Year since 1900
    ttm.tm_mon = mm - 1; // Month since January 
    ttm.tm_mday = dd; // Day of the month [1-31]
    ttm.tm_hour = HH; // Hour of the day [00-23]
    ttm.tm_min = MM;
    ttm.tm_sec = SS;

    time_t ttime_t = mktime(&ttm);

    system_clock::time_point time_point_result = std::chrono::system_clock::from_time_t(ttime_t);

    time_point_result += std::chrono::milliseconds(fff);
    return time_point_result;
}

std::string time_point_to_string(std::chrono::system_clock::time_point &tp)
{
    using namespace std;
    using namespace std::chrono;

    auto ttime_t = system_clock::to_time_t(tp);
    auto tp_sec = system_clock::from_time_t(ttime_t);
    milliseconds ms = duration_cast<milliseconds>(tp - tp_sec);

    std::tm * ttm = localtime(&ttime_t);

    char date_time_format[] = "%Y.%m.%d-%H.%M.%S";

    char time_str[] = "yyyy.mm.dd.HH-MM.SS.fff";

    strftime(time_str, strlen(time_str), date_time_format, ttm);

    string result(time_str);
    result.append(".");
    result.append(to_string(ms.count()));

    return result;
}

答案 4 :(得分:3)

我会把这个放在对已接受答案的评论中,因为那是它所属的地方,但我不能。所以,万一有人得到不可靠的结果,这可能是原因。

小心接受的答案,如果time_point在纪元之前,它就会失败。

这行代码:

std::size_t fractional_seconds = ms.count() % 1000;
如果ms.count()为负数,则

将产生意外值(因为size_t不意味着保持负值)。

答案 5 :(得分:0)

在我的情况下,我使用chrono和c函数localtime_r是线程安全的(与std :: localtime相反)。

#include <iostream>
#include <chrono>
#include <ctime>
#include <time.h>
#include <iomanip>


int main() {
  std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
  std::time_t currentTime = std::chrono::system_clock::to_time_t(now);
  std::chrono::milliseconds now2 = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
  struct tm currentLocalTime;
  localtime_r(&currentTime, &currentLocalTime);
  char timeBuffer[80];
  std::size_t charCount { std::strftime( timeBuffer, 80,
                                         "%b %d %T",
                                          &currentLocalTime)
                         };

  if (charCount == 0) return -1;

  std::cout << timeBuffer << "." << std::setfill('0') << std::setw(3) << now2.count() % 1000 << std::endl;
  return 0;
}

答案 6 :(得分:0)

如果要以numpy datetime64的格式格式化system_clock::time_point,则可以使用:

std::string format_time_point(system_clock::time_point point)
{
    static_assert(system_clock::time_point::period::den == 1000000000 && system_clock::time_point::period::num == 1);
    std::string out(29, '0');
    char* buf = &out[0];
    std::time_t now_c = system_clock::to_time_t(point);
    std::strftime(buf, 21, "%Y-%m-%dT%H:%M:%S.", std::localtime(&now_c));
    sprintf(buf+20, "%09ld", point.time_since_epoch().count() % 1000000000);
    return out;
}

示例输出:2019-11-19T17:59:58.425802666