c++ - 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 秒。我坚持使用偏移/增量部分
解决方案
只需将偏移量添加到自纪元以来的秒数。
std::time_t t = std::time(nullptr) + offset;
您还可以offset
使用 type std::time_t
,因为它表示以秒为单位的时间距离。
推荐阅读
- javascript - 出现错误“Route.post() 需要回调函数,但得到了 [object Undefined]”
- android - Flutter 无法识别安卓设备
- c# - 如何在 .NET Core 2.1 的 Application Insights 中从采样中排除异常和错误日志记录?
- c++ - 适用于 Windows x86 的 PostgreSQL 11 安装程序?
- python - 解密错误 - 可能与 fernet 有关
- sql - Int to Time - 需要帮助理解其背后的逻辑
- azure - 从 VS Code 使用 Deploy to Web 应用程序时无法加载站点
- python - Pandas 日期时间索引:随着时间的推移当前事件的数量
- amazon-web-services - 有没有办法在 aws lambda 层中定义一个通用的环境变量?
- autodesk-forge - 如何以最快的方式使用 dbIds 为大量项目着色?