linux 系统时间打印成字符串
时间: 2023-12-19 19:04:37 浏览: 43
可以使用以下命令将 Linux 系统时间打印成字符串:
```shell
date +"%Y-%m-%d %H:%M:%S"
```
其中,`date` 命令用于获取系统时间,`+"%Y-%m-%d %H:%M:%S"` 用于指定输出格式,其中 `%Y` 表示年份,`%m` 表示月份,`%d` 表示日,`%H` 表示小时,`%M` 表示分钟,`%S` 表示秒。输出格式可以根据需要进行修改。
相关问题
linux 使用sprintf系统时间打印成字符串
以下是一个例子:
```
#include <stdio.h>
#include <time.h>
int main() {
char time_string[20];
time_t raw_time;
struct tm * time_info;
time(&raw_time);
time_info = localtime(&raw_time);
sprintf(time_string, "%d-%02d-%02d %02d:%02d:%02d",
time_info->tm_year + 1900, time_info->tm_mon + 1, time_info->tm_mday,
time_info->tm_hour, time_info->tm_min, time_info->tm_sec);
printf("Current time: %s\n", time_string);
return 0;
}
```
输出结果类似于:
```
Current time: 2021-03-05 23:59:59
```
linux驱动中怎么以年月日时分秒的格式打印当前系统时间
在 Linux 驱动中,可以使用 `struct timespec` 结构体来获取当前系统时间,然后使用 `localtime` 函数将其转换为本地时间,最后使用 `strftime` 函数以指定的格式打印出来。
以下是示例代码:
```c
#include <linux/time.h>
#include <linux/module.h>
#include <linux/init.h>
MODULE_LICENSE("GPL");
static int __init my_init(void)
{
struct timespec ts;
struct tm tm;
char buf[20];
getnstimeofday(&ts); // 获取当前系统时间
time_to_tm(ts.tv_sec, 0, &tm); // 将时间转换为本地时间
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tm); // 格式化时间字符串
printk(KERN_INFO "Current system time: %s\n", buf); // 打印时间字符串
return 0;
}
static void __exit my_exit(void)
{
printk(KERN_INFO "Goodbye!\n");
}
module_init(my_init);
module_exit(my_exit);
```
这个驱动模块在加载时会打印当前系统时间,格式为 `YYYY-MM-DD HH:MM:SS`,例如:
```
[ 129.192000] Current system time: 2022-05-08 22:15:34
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)