You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中如何实现带timedelta偏移的strftime时间格式化功能

实现方案

核心逻辑非常简单:C++标准库中std::time_t类型本身就是以秒为单位的整数时间戳,直接对其做加减运算即可实现秒级的时间偏移,完全匹配你Python代码中timedelta(seconds=offset)的效果。

修改后的完整代码

#include <iostream>
#include <ctime>
#include <string>

// offset参数单位为秒,默认值0对应无偏移
std::string current_datetime(std::string timezone = "Z", int offset = 0)
{
  std::time_t t = std::time(nullptr);
  // 直接对时间戳加偏移量即可完成时间调整
  t += offset;
  char mbstr[50];
  // 如需使用UTC时间而非本地时间,可将localtime改为gmtime
  std::strftime(mbstr, sizeof(mbstr), "%Y-%m-%dT%H:%M:%S", std::localtime(&t));
  std::string formated_date(mbstr);
  formated_date += timezone;
  return formated_date;
}

int main() 
{
    // 开始时间:当前时间无偏移
    std::cout << "开始日期:" << current_datetime() << std::endl;
    // 结束时间:未来120秒的时间
    std::cout << "结束日期:" << current_datetime("Z", 120) << std::endl;
    // 自定义时区的结束时间示例
    std::cout << "自定义时区结束日期:" << current_datetime("-03:00", 120) << std::endl;
    return 0;
}

关键改动说明

  • 将offset参数默认值改为0,匹配Python代码中无偏移的默认行为
  • 直接修改std::time_t类型的时间戳,不需要额外引入复杂的时间计算逻辑
  • 如需更高精度的时间偏移(如毫秒、微秒级),可以改用C++11及以上版本提供的<chrono>库实现

内容的提问来源于stack exchange,提问作者rockstiff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 20:06:02