linux时间转换函数
- 一.linux
- 二.python
一.linux
cat > linux_time.c <<-'EOF' #define _GNU_SOURCE #include
#include #include #include #include int main(int argc,char*argv[]) { char date_string[128]={0}; // 1.获取当前系统时间,精确到毫秒 方法1 { struct timeb tTimeB; ftime(&tTimeB); struct tm *tm = localtime(&tTimeB.time); sprintf(date_string,"%04d-%02d-%02d %02d:%02d:%02d.%03d", tm->tm_year + 1900,tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec,tTimeB.millitm); printf("%s\n",date_string); } // 2.获取当前系统时间,精确到毫秒 方法2 { struct timespec ts; char buffer[30]; clock_gettime(CLOCK_REALTIME, &ts); struct tm *tm = localtime(&ts.tv_sec); strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm); printf("%s.%03d\n", buffer, ts.tv_nsec/1000/1000); } // 3.字符串转时间 { struct tm tm; memset(&tm,0,sizeof(tm)); //如果不清空mktime偶尔会失败 long milliseconds; char*end_ptr = strptime(date_string, "%Y-%m-%d %H:%M:%S", &tm); if (end_ptr == NULL) { fprintf(stderr, "Failed to parse date string:%s\n",date_string); return 1; } if (*end_ptr == '.') { milliseconds = strtol(end_ptr + 1, NULL, 10); } else { milliseconds = 0; } time_t t = mktime(&tm); if (t == -1) { fprintf(stderr, "Failed to convert tm to time_t:%s\n",date_string,t); return 1; } struct timespec ts; ts.tv_sec = t; ts.tv_nsec = milliseconds * 1000000L; printf("%04d-%02d-%02d %02d:%02d:%02d.%03d\n", tm.tm_year + 1900,tm.tm_mon + 1,tm.tm_mday, tm.tm_hour,tm.tm_min,tm.tm_sec,milliseconds); } } EOF gcc -o linux_time linux_time.c ./linux_time 二.python
cat > test_time.py <<-'EOF' from datetime import datetime # 1.获取当前系统时间 now = datetime.now() # 2.格式化为字符串 time_str=now.strftime("%Y-%m-%d %H:%M:%S.%f") print(time_str) # 3.字符串转时间 time=datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S.%f") # 4.时间转字符串输出 print(time.strftime("%Y-%m-%d %H:%M:%S.%f")) EOF python3 test_time.py
还没有评论,来说两句吧...