LINUX C系统编程与PYTHON中的时间模块对比

简介: 今天看python时间模块time的时候发现和LINUX系统编程中的时间调用函数基本一样,以前刚好没有好好学习LINUX C编程的时间模块就对比进行了学习。 本文只是给出函数接口和使用方式,详细了解请参考LINUX main page和PYTHO...

今天看python时间模块time的时候发现和LINUX系统编程中的时间调用函数基本一样,以前刚好没有好好学习LINUX C编程的时间模块就对比进行了学习。

  • 本文只是给出函数接口和使用方式,详细了解请参考LINUX main page和PYTHON help
  • 本文不涉及asctime和ctime,并且C中涉及多线程编程注意选择可重入性函数

一、时间存在方式

其实不管是C还是PYTHON这里都包含3种时间不同存在的方式

  • 日历时间:Epoch以来的秒及新纪元时间(1970年1月1日 00:00:00)以来的秒
  • 分解时间:实际上是时间在程序内部存在的结构,也是一个中间介质,C中使用结构体,PYTHON中使用元组
  1. LINUX C为tm结构体:
struct tm {
              int tm_sec;         /* seconds */
              int tm_min;         /* minutes */
              int tm_hour;        /* hours */
              int tm_mday;        /* day of the month */
              int tm_mon;         /* month */
              int tm_year;        /* year */
              int tm_wday;        /* day of the week */
              int tm_yday;        /* day in the year */
              int tm_isdst;       /* daylight saving time */
                                  /* >0 DST is in effect
                                     =0 DST is not effect;
                                     <0 DST information not available
                                   */         
          }; 
  1. PYTHON struct_time元组:
索引(Index)   属性(Attribute)   
0               tm_year(年)     
1               tm_mon(月)    
2               tm_mday(日)  
3               tm_hour(时)  
4               tm_min(分)    
5               tm_sec(秒)   
6               tm_wday(weekday)     
7               tm_yday(一年中的第几天)    
8               tm_isdst(是否是夏令时) 

可以看到他们基本是一致的

  • 可读时间:这种一般就是我们平时看到的一些方便读取的的时间,比如
2017-10-12 06:52:03(AM) +0800 

就是方便人类读取的可读取时间

LINUX C可读时间格式:

%a     The abbreviated weekday name according to the current locale.
%A     The full weekday name according to the current locale.
%b     The abbreviated month name according to the current locale.
%B     The full month name according to the current locale.
%c     The preferred date and time representation for the current locale.
%C     The century number (year/100) as a 2-digit integer. (SU)
%d     The day of the month as a decimal number (range 01 to 31).
%D     Equivalent  to  %m/%d/%y.   (Yecch—for  Americans only.  Americans should note that in other countries %d/%m/%y is rather common.  This means that in
      international context this format is ambiguous and should not be used.) (SU)
%e     Like %d, the day of the month as a decimal number, but a leading zero is replaced by a space. (SU)
%E     Modifier: use alternative format, see below. (SU)
%F     Equivalent to %Y-%m-%d (the ISO 8601 date format). (C99)
%G     The ISO 8601 week-based year (see NOTES) with century as a decimal number.  The 4-digit year corresponding to the ISO week number (see %V).  This has
      the same format and value as %Y, except that if the ISO week number belongs to the previous or next year, that year is used instead. (TZ)
%g     Like %G, but without century, that is, with a 2-digit year (00-99). (TZ)
%h     Equivalent to %b.  (SU)
%H     The hour as a decimal number using a 24-hour clock (range 00 to 23).
%I     The hour as a decimal number using a 12-hour clock (range 01 to 12).
%j     The day of the year as a decimal number (range 001 to 366).
%k     The hour (24-hour clock) as a decimal number (range 0 to 23); single digits are preceded by a blank.  (See also %H.)  (TZ)
%l     The hour (12-hour clock) as a decimal number (range 1 to 12); single digits are preceded by a blank.  (See also %I.)  (TZ)
%m     The month as a decimal number (range 01 to 12).
%M     The minute as a decimal number (range 00 to 59).
%n     A newline character. (SU)
%O     Modifier: use alternative format, see below. (SU)
%p     Either  "AM" or "PM" according to the given time value, or the corresponding strings for the current locale.  Noon is treated as "PM" and midnight as
      "AM".
%P     Like %p but in lowercase: "am" or "pm" or a corresponding string for the current locale. (GNU)
%r     The time in a.m. or p.m. notation.  In the POSIX locale this is equivalent to %I:%M:%S %p.  (SU)
%R     The time in 24-hour notation (%H:%M).  (SU) For a version including the seconds, see %T below.
%s     The number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). (TZ)
%S     The second as a decimal number (range 00 to 60).  (The range is up to 60 to allow for occasional leap seconds.)
%t     A tab character. (SU)
%T     The time in 24-hour notation (%H:%M:%S).  (SU)
%u     The day of the week as a decimal, range 1 to 7, Monday being 1.  See also %w.  (SU)
%U     The week number of the current year as a decimal number, range 00 to 53, starting with the first Sunday as the first day of week 01.  See also %V and
      %W.
%V     The ISO 8601 week number (see NOTES) of the current year as a decimal number, range 01 to 53, where week 1 is the first week that has at least 4 days
      in the new year.  See also %U and %W.  (SU)
%w     The day of the week as a decimal, range 0 to 6, Sunday being 0.  See also %u.
%W     The week number of the current year as a decimal number, range 00 to 53, starting with the first Monday as the first day of week 01.
%x     The preferred date representation for the current locale without the time.
%X     The preferred time representation for the current locale without the date.
%y     The year as a decimal number without a century (range 00 to 99).
%Y     The year as a decimal number including the century.
%z     The +hhmm or -hhmm numeric timezone (that is, the hour and minute offset from UTC). (SU)
%Z     The timezone name or abbreviation.
%+     The date and time in date(1) format. (TZ) (Not supported in glibc2.)
%%     A literal '%' character. 

python 可读时间格式:

%Y  Year with century as a decimal number.
%m  Month as a decimal number [01,12].
%d  Day of the month as a decimal number [01,31].
%H  Hour (24-hour clock) as a decimal number [00,23].
%M  Minute as a decimal number [00,59].
%S  Second as a decimal number [00,61].
%z  Time zone offset from UTC.
%a  Locale's abbreviated weekday name.
%A  Locale's full weekday name.
%b  Locale's abbreviated month name.
%B  Locale's full month name.
%c  Locale's appropriate date and time representation.
%I  Hour (12-hour clock) as a decimal number [01,12].
%p  Locale's equivalent of either AM or PM.

Other codes may be available on your platform.  See documentation for
the C library strftime function. 

本文使用这三个术语

二、日历时间

下面方法获取当前系统时间的当前时间

  • LINUX C:
    int gettimeofday(struct timeval *tv,struct timezone *tz);
    time_t time(time_t *timep)
  • PYTHON:
    time.time()
    上面的方式都是获取当前时间的日历时间的方式为了方便我们使用time方法

三、日历时间转换为分解时间

  • LINUX C:
    strcut tm* gmtime(const time_t* timep);
    strcut tm* localtime(const time_t* timep);
Each of these functions returns the value described, or NULL  in case an error was detected. 
  • PYTHON:
    time.gmtime(seconds=None)
    time.localtime(seconds=None)

可以看到他们是一致的其中gmtime代表返回UTC时间,而localtime代表返回本地时区时间

四、将分解时间转换为日历时间

  • LINUX C:
    time_t mktime(struct tm* tmieptr)
RETURN VALUE
      -1 in case of mktime() in case an error was detected. 
  • PYTHON:
    time.mktime(p_tuple)

五、将分解时间转换为可读时间

  • LINUX C:
    size_t strftime(char *s, size_t max, const char *format,const struct tm *tm);
RETURN VALUE
      Provided that the result string, including the terminating null byte, does not exceed max bytes, strftime() returns the number of bytes (excluding the ter‐
      minating  null  byte)  placed  in the array s.  If the length of the result string (including the terminating null byte) would exceed max bytes, then strf‐
      time() returns 0, and the contents of the array are undefined.  (This behavior applies since at least libc 4.4.4; very old versions of libc, such  as  libc
      4.4.1, would return max if the array was too small.)

      Note  that the return value 0 does not necessarily indicate an error.  For example, in many locales %p yields an empty string.  An empty format string will
      likewise yield an empty string. 
  • PYTHON:
    strftime(format, p_tuple=None)

这里需要注意format,format在文章开头已经给出

六、将可读时间转换为分解时间

  • LINUX C:
    char *strptime(const char *s, const char *format, struct tm *tm);
RETURN VALUE
      The return value of the function is a pointer to the first character not processed in this function call.  In case the input string contains  more  charac‐
      ters  than required by the format string the return value points right after the last consumed input character.  In case the whole input string is consumed
      the return value points to the null byte at the end of the string.  If strptime() fails to match all of the format string and therefore an  error  occurred
      the function returns NULL. 
  • PYTHON:
    strptime(string, format)
    这里需要注意format,format在文章开头已经给出

七、转换图

这里给出一张LINUX系统编程手册里面的一张图,其实python是一样的,红色箭头是本文涉及的函数

Paste_Image.png
Paste_Image.png

八、方法使用举例

下面使用C和PYTHON分别实现将日期

2017-10-12 08:52:03(AM) CST 

转换分解时间,日历时间然后再减去3600秒转换回分解时间和可读时间的小程序,以熟悉使用方式

  • C程序:
/*************************************************************************
 > File Name: testtime.c
 > Author: gaopeng QQ:22389860 all right reserved
 > Mail: gaopp_200217@163.com
 > Created Time: Wed 01 Nov 2017 02:28:25 AM CST
************************************************************************/

#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#define MAXSIZE 99


int  rtime2ctime(/*in*/const char* r_time,/*out*/time_t* ctime)
{
       time_t i_ctime;
       struct tm tm_st;
       //此处根据固定测试转换为分解时间tm_st
       if ( !strptime(r_time,"%Y-%m-%d %X(%p) %z",&tm_st))
       {
               return -1;
       }

       //此处将分解时间tm_st转换为日历时间ctime
       if( (*ctime = mktime(&tm_st)) == -1)
       {
               return -1;
       }

       return 0;
}


int ctime2rtime(/*in*/time_t c_time)
{

       struct tm* tm_st = NULL;
       char time[MAXSIZE] ;
       //此处将日历时间转换为分解时间
       if((tm_st = localtime(&c_time)) == NULL)
       {
               return -1;
       }


       //此处将分解时间转换为可读时间
       if(strftime(time,MAXSIZE-1,"%Y-%m-%d %X(%p) %z",tm_st) == 0)
       {
               return -1;
       }

       printf("%s\n",time);
       return 0;
}



int main(void)
{
       char r_time[100] = "2017-10-12 07:52:03(AM) +0800";
       time_t ctime;

       if( rtime2ctime(r_time,&ctime) == -1 )
       {
               printf("rtime2ctime error\n");
               return -1;
       }

       printf("2017-10-12 07:52:03(AM) +0800 to calenlar time is:%ld\n",ctime);

       ctime = ctime - (time_t)3600;


       printf("after sub 1 hours time is:");

       if(ctime2rtime(ctime) == -1)
       {
               printf("ctime2rtime error\n");
       }

} 
  • python程序:
import time

def rtime2ctime(r_time):
    #此处根据固定测试可读时间转换为分解时间
    p_time = time.strptime(r_time,"%Y-%m-%d %X(%p) %z")
    #此处将分解时间tm_st转换为日历时间
    return time.mktime(p_time)

def ctime2rtime(ctime):
    #此处将日历时间转换为分解时间
    p_time = time.localtime(ctime)
    #此处将分解时间转换为可读时间
    r_time = time.strftime("%Y-%m-%d %X(%p) %z",p_time)
    return r_time

r_time="2017-10-12 06:52:03(AM) +0800"
ctime = rtime2ctime(r_time)
print("2017-10-12 06:52:03(AM) +0800 to calenlar time is:%d" %(ctime))
ctime = ctime - 3600
print("after sub 1 hours time is:%s" %(ctime2rtime(ctime))) 

他们的运行结果均是:

2017-10-12 06:52:03(AM) +0800 to calenlar time is:1507762323
after sub 1 hours time is:2017-10-12 05:52:03(AM) +0800 

作者微信:

微信.jpg
微信.jpg
目录
打赏
0
0
0
0
91
分享
相关文章
[oeasy]python081_ai编程最佳实践_ai辅助编程_提出要求_解决问题
本文介绍了如何利用AI辅助编程解决实际问题,以猫屎咖啡的购买为例,逐步实现将购买斤数换算成人民币金额的功能。文章强调了与AI协作时的三个要点:1) 去除无关信息,聚焦目标;2) 将复杂任务拆解为小步骤,逐步完成;3) 巩固已有成果后再推进。最终代码实现了输入验证、单位转换和价格计算,并保留两位小数。总结指出,在AI时代,人类负责明确目标、拆分任务和确认结果,AI则负责生成代码、解释含义和提供优化建议,编程不会被取代,而是会更广泛地融入各领域。
63 28
|
15天前
|
Linux系统资源管理:多角度查看内存使用情况。
要知道,透过内存管理的窗口,我们可以洞察到Linux系统运行的真实身姿,如同解剖学家透过微观镜,洞察生命的奥秘。记住,不要惧怕那些高深的命令和参数,他们只是你掌握系统"魔法棒"的钥匙,熟练掌握后,你就可以骄傲地说:Linux,我来了!
91 27
|
19天前
|
Linux系统ext4磁盘扩容实践指南
这个过程就像是给你的房子建一个新的储物间。你需要先找到空地(创建新的分区),然后建造储物间(格式化为ext4文件系统),最后将储物间添加到你的房子中(将新的分区添加到文件系统中)。完成这些步骤后,你就有了一个更大的储物空间。
81 10
|
25天前
|
[oeasy]python074_ai辅助编程_水果程序_fruits_apple_banana_加法_python之禅
本文回顾了从模块导入变量和函数的方法,并通过一个求和程序实例,讲解了Python中输入处理、类型转换及异常处理的应用。重点分析了“明了胜于晦涩”(Explicit is better than implicit)的Python之禅理念,强调代码应清晰明确。最后总结了加法运算程序的实现过程,并预告后续内容将深入探讨变量类型的隐式与显式问题。附有相关资源链接供进一步学习。
33 4
|
1月前
|
Linux系统中如何查看CPU信息
本文介绍了查看CPU核心信息的方法,包括使用`lscpu`命令和读取`/proc/cpuinfo`文件。`lscpu`能快速提供逻辑CPU数量、物理核心数、插槽数等基本信息;而`/proc/cpuinfo`则包含更详细的配置数据,如核心ID和处理器编号。此外,还介绍了如何通过`lscpu`和`dmidecode`命令获取CPU型号、制造商及序列号,并解释了CPU频率与缓存大小的相关信息。最后,详细解析了`lscpu`命令输出的各项参数含义,帮助用户更好地理解CPU的具体配置。
104 8
在线编程实现!如何在Java后端通过DockerClient操作Docker生成python环境
以上内容是一个简单的实现在Java后端中通过DockerClient操作Docker生成python环境并执行代码,最后销毁的案例全过程,也是实现一个简单的在线编程后端API的完整流程,你可以在此基础上添加额外的辅助功能,比如上传文件、编辑文件、查阅文件、自定义安装等功能。 只有锻炼思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
在线编程实现!如何在Java后端通过DockerClient操作Docker生成python环境
Python 高级编程与实战:构建 RESTful API
本文深入探讨了使用 Python 构建 RESTful API 的方法,涵盖 Flask、Django REST Framework 和 FastAPI 三个主流框架。通过实战项目示例,详细讲解了如何处理 GET、POST 请求,并返回相应数据。学习这些技术将帮助你掌握构建高效、可靠的 Web API。
深度体验阿里云系统控制台:SysOM 让 Linux 服务器监控变得如此简单
作为一名经历过无数个凌晨三点被服务器报警电话惊醒的运维工程师,我对监控工具有着近乎苛刻的要求。记得去年那次大型活动,我们的主站流量暴增,服务器内存莫名其妙地飙升到90%以上,却找不到原因。如果当时有一款像阿里云 SysOM 这样直观的监控工具,也许我就不用熬通宵排查问题了。今天,我想分享一下我使用 SysOM 的亲身体验,特别是它那令人印象深刻的内存诊断功能。
Python 高级编程与实战:构建自动化测试框架
本文深入探讨了Python中的自动化测试框架,包括unittest、pytest和nose2,并通过实战项目帮助读者掌握这些技术。文中详细介绍了各框架的基本用法和示例代码,助力开发者快速验证代码正确性,减少手动测试工作量。学习资源推荐包括Python官方文档及Real Python等网站。
|
20天前
|
微服务2——MongoDB单机部署4——Linux系统中的安装启动和连接
本节主要介绍了在Linux系统中安装、启动和连接MongoDB的详细步骤。首先从官网下载MongoDB压缩包并解压至指定目录,接着创建数据和日志存储目录,并配置`mongod.conf`文件以设定日志路径、数据存储路径及绑定IP等参数。之后通过配置文件启动MongoDB服务,并使用`mongo`命令或Compass工具进行连接测试。此外,还提供了防火墙配置建议以及服务停止的两种方法:快速关闭(直接杀死进程)和标准关闭(通过客户端命令安全关闭)。最后补充了数据损坏时的修复操作,确保数据库的稳定运行。
55 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等