首页 > 解决方案 > C++ timedelta 与 strftime?

问题描述

我想做一个函数来获取具有某种格式的当前时间。C++ 不是我的主要语言,但我正在尝试这样做:

current_datetime(timezone='-03:00', offset=timedelta(seconds=120))
def current_datetime(fmt='%Y-%m-%dT%H:%M:%S', timezone='Z', offset=None):
    offset = offset or timedelta(0)
    return (datetime.today() + offset).strftime(fmt) + timezone

到目前为止,我最好的互联网搜索是这个,但缺少偏移部分:

#include <iostream>
#include <ctime>

std::string current_datetime(std::string timezone="Z", int offset=1)
{
  std::time_t t = std::time(nullptr);
  char mbstr[50];
  std::strftime(mbstr, sizeof(mbstr), "%Y-%m-%dT%H:%M:%S", std::localtime(&t));
  std::string formated_date(mbstr);
  formated_date += std::string(timezone);
  return formated_date;
}

int main() 
{
    std::cout << current_datetime() << std::endl; //2021-10-26T21:34:48Z
    std::cout << current_datetime("-05:00") << std::endl; //2021-10-26T21:34:48-05:00
    return 0;
}

这个想法是得到一个字符串,它是一个“开始日期”和一个作为“结束日期”的字符串,它是未来 X 秒。我坚持使用偏移/增量部分

标签: c++timetimedeltastrftime

解决方案


只需将偏移量添加到自纪元以来的秒数。

std::time_t t = std::time(nullptr) + offset;

您还可以offset使用 type std::time_t,因为它表示以秒为单位的时间距离。


推荐阅读