C
1.简介:
在C语言中可以使用函数gettimeofday()函数来得到时间,它的精度可以达到微妙。
2.函数原型:
#include<sys/time.h>
int gettimeofday(struct timeval*tv,struct timezone *tz )
3.说明:
gettimeofday()会把目前的时间用tv 结构体返回,当地时区的信息则放到tz所指的结构中
4.结构体:
1>timeval
struct timeval{
long tv_sec;/*秒*/
long tv_usec;/*微妙*/
};
2>timezone 结构定义为:
struct timezone{
int tz_minuteswest;/*和greenwich 时间差了多少分钟*/
int tz_dsttime;/*type of DST correction*/
}
3>在gettimeofday()函数中tv或者tz都可以为空。如果为空则就不返回其对应的结构体。
4>函数执行成功后返回0,失败后返回-1,错误代码存于errno中。
5.程序实例:
*#include <time.h>
#include <sys/time.h>
#include <stdio.h>
void main(void)
{
struct timeval tv;
struct timezone tz;
struct tm *p;
gettimeofday(&tv, &tz);
p = localtime(&tv.tv_sec);
printf("The precise microseconds time :%d-%d-%d-%d-%d-%d.%ld\n", 1900+p->tm_year, 1+p->tm_mon, p->tm_mday, p-
>tm_hour, p->tm_min, p->tm_sec, tv.tv_usec);
}
6. struct tm
在time.h中的定义的tm结构来获得日期和时间。
struct tm {
int tm_sec; /* 秒 – 取值区间为[0,59] */
int tm_min; /* 分 - 取值区间为[0,59] */
int tm_hour; /* 时 - 取值区间为[0,23] */
int tm_mday; /* 一个月中的日期 - 取值区间为[1,31] */
int tm_mon; /* 月份(从一月开始,0代表一月) - 取值区间为[0,11] */
int tm_year; /* 年份,其值等于实际年份减去1900 */
int tm_wday; /* 星期 – 取值区间为[0,6],其中0代表星期天,1代表星期一,以此类推 */
int tm_yday; /* 从每年的1月1日开始的天数 – 取值区间为[0,365],其中0代表1月1日,1代表1月2日,以此类推 */
int tm_isdst; /* 夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的进候,tm_isdst为0;不了解情况时,tm_isdst()为负。*/
}
7. localtime()
根据给定的与1970年1月1日相减得秒数,取得当地的时区的时间和日期
python
from datetime import *
import time
dt = datetime.now()
print dt.strftime('%Y-%m-%d-%H-%M-%S.%f')