python中datetime在c++中代码
时间: 2023-11-28 09:48:25 浏览: 48
在C++中,可以使用C++11引入的std::chrono库来实现类似于Python中datetime的日期和时间操作。以下是一个简单的示例代码:
```c++
#include <iostream>
#include <chrono>
int main() {
// 获取当前时间
auto now = std::chrono::system_clock::now();
std::time_t now_time = std::chrono::system_clock::to_time_t(now);
std::cout << "Current time: " << std::ctime(&now_time);
// 获取当前日期
auto now_date = std::chrono::system_clock::now();
std::time_t now_date_time = std::chrono::system_clock::to_time_t(now_date);
std::tm now_tm = *std::localtime(&now_date_time);
std::cout << "Current date: " << now_tm.tm_year + 1900 << "-" << now_tm.tm_mon + 1 << "-" << now_tm.tm_mday << std::endl;
// 时间加减
auto future = now + std::chrono::hours(24);
std::time_t future_time = std::chrono::system_clock::to_time_t(future);
std::cout << "Future time: " << std::ctime(&future_time);
return 0;
}
```
此代码使用std::chrono::system_clock类获取当前时间,将其转换为std::time_t类型,然后使用std::ctime函数将其格式化为可读日期时间字符串。在获取当前日期时,代码将当前时间转换为std::time_t类型,然后使用std::localtime函数将其转换为std::tm类型,该类型包含了年、月、日等日期信息。在时间加减方面,代码使用std::chrono::hours来表示24小时,然后将其与当前时间相加得到未来时间。