溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

LINUX C系統(tǒng)編程與PYTHON中的時(shí)間模塊對(duì)比是怎樣的

發(fā)布時(shí)間:2021-12-04 17:29:26 來源:億速云 閱讀:122 作者:柒染 欄目:互聯(lián)網(wǎng)科技

LINUX C系統(tǒng)編程與PYTHON中的時(shí)間模塊對(duì)比是怎樣的,針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡(jiǎn)單易行的方法。

今天看python時(shí)間模塊time的時(shí)候發(fā)現(xiàn)和LINUX系統(tǒng)編程中的時(shí)間調(diào)用函數(shù)基本一樣,以前剛好沒有好好學(xué)習(xí)LINUX C編程的時(shí)間模塊就對(duì)比進(jìn)行了學(xué)習(xí)。

一、時(shí)間存在方式

其實(shí)不管是C還是PYTHON這里都包含3種時(shí)間不同存在的方式

  • 日歷時(shí)間:Epoch以來的秒及新紀(jì)元時(shí)間(1970年1月1日 00:00:00)以來的秒

  • 分解時(shí)間:實(shí)際上是時(shí)間在程序內(nèi)部存在的結(jié)構(gòu),也是一個(gè)中間介質(zhì),C中使用結(jié)構(gòu)體,PYTHON中使用元組

  1. LINUX C為tm結(jié)構(gòu)體:

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(時(shí))  
4               tm_min(分)    
5               tm_sec(秒)   
6               tm_wday(weekday)     
7               tm_yday(一年中的第幾天)    
8               tm_isdst(是否是夏令時(shí))

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

  • 可讀時(shí)間:這種一般就是我們平時(shí)看到的一些方便讀取的的時(shí)間,比如

2017-10-12 06:52:03(AM) +0800

就是方便人類讀取的可讀取時(shí)間

LINUX C可讀時(shí)間格式:

%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 可讀時(shí)間格式:

%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.

本文使用這三個(gè)術(shù)語

二、日歷時(shí)間

下面方法獲取當(dāng)前系統(tǒng)時(shí)間的當(dāng)前時(shí)間

  • LINUX C:
    int gettimeofday(struct timeval *tv,struct timezone *tz);
    time_t time(time_t *timep)

  • PYTHON:
    time.time()
    上面的方式都是獲取當(dāng)前時(shí)間的日歷時(shí)間的方式為了方便我們使用time方法

三、日歷時(shí)間轉(zhuǎn)換為分解時(shí)間

  • 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)

可以看到他們是一致的其中g(shù)mtime代表返回UTC時(shí)間,而localtime代表返回本地時(shí)區(qū)時(shí)間

四、將分解時(shí)間轉(zhuǎn)換為日歷時(shí)間

  • 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)

五、將分解時(shí)間轉(zhuǎn)換為可讀時(shí)間

  • 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在文章開頭已經(jīng)給出

六、將可讀時(shí)間轉(zhuǎn)換為分解時(shí)間

  • 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在文章開頭已經(jīng)給出

七、轉(zhuǎn)換圖

這里給出一張LINUX系統(tǒng)編程手冊(cè)里面的一張圖,其實(shí)python是一樣的,紅色箭頭是本文涉及的函數(shù)

LINUX C系統(tǒng)編程與PYTHON中的時(shí)間模塊對(duì)比是怎樣的

Paste_Image.png

八、方法使用舉例

下面使用C和PYTHON分別實(shí)現(xiàn)將日期

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

轉(zhuǎn)換分解時(shí)間,日歷時(shí)間然后再減去3600秒轉(zhuǎn)換回分解時(shí)間和可讀時(shí)間的小程序,以熟悉使用方式

  • 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;
       //此處根據(jù)固定測(cè)試轉(zhuǎn)換為分解時(shí)間tm_st
       if ( !strptime(r_time,"%Y-%m-%d %X(%p) %z",&tm_st))
       {
               return -1;
       }

       //此處將分解時(shí)間tm_st轉(zhuǎn)換為日歷時(shí)間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] ;
       //此處將日歷時(shí)間轉(zhuǎn)換為分解時(shí)間
       if((tm_st = localtime(&c_time)) == NULL)
       {
               return -1;
       }


       //此處將分解時(shí)間轉(zhuǎn)換為可讀時(shí)間
       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):
    #此處根據(jù)固定測(cè)試可讀時(shí)間轉(zhuǎn)換為分解時(shí)間
    p_time = time.strptime(r_time,"%Y-%m-%d %X(%p) %z")
    #此處將分解時(shí)間tm_st轉(zhuǎn)換為日歷時(shí)間
    return time.mktime(p_time)

def ctime2rtime(ctime):
    #此處將日歷時(shí)間轉(zhuǎn)換為分解時(shí)間
    p_time = time.localtime(ctime)
    #此處將分解時(shí)間轉(zhuǎn)換為可讀時(shí)間
    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)))

他們的運(yùn)行結(jié)果均是:

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

關(guān)于LINUX C系統(tǒng)編程與PYTHON中的時(shí)間模塊對(duì)比是怎樣的問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI