time模块学习

来源:互联网 发布:自拍换装软件 编辑:程序博客网 时间:2024/05/17 23:20

time模块是关于时间的模块,有一些时间转换的api。一般来讲,我们有时候会在数据库里存储一个时间戳,这个时间戳是一个浮点数。这样便于进行时间计算。比如:1400422272.003237。我们有一个开始时间,在unix操作系统下,这个时间是1970.

>>> time.gmtime(0)time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
我么用gmtime(0)这个函数就能够查看epoch。

>>> time.time()1400422272.003237
time.time()生成现在的时间,unix时间,浮点数显示。

>>> time.ctime()'Sun May 18 22:16:13 2014'
time.ctime()也是显示现在时间,但是是用一个比较友好的格式化时间来显示。

那么我们怎么把浮点数的时间戳转化为字符串的友好显示??下面这张表告诉了我们。怎么在时间戳和格式化的时间进行转换。

From
To
Use
seconds since the epoch
struct_time in UTC
gmtime()
seconds since the epoch
struct_time in local time
localtime()
struct_time in UTC
seconds since the epoch
calendar.timegm()
struct_time in local time
seconds since the epoch
mktime()
比如我们要把一个时间戳转化成"%Y-%m-%d"格式的字符串。

思路是:时间戳—>struct_time—>字符串

>>> t=time.time()>>> t1400423512.412923>>> t_=time.localtime(t)>>> t_time.struct_time(tm_year=2014, tm_mon=5, tm_mday=18, tm_hour=22, tm_min=31, tm_sec=52, tm_wday=6, tm_yday=138, tm_isdst=0)>>> t_str=time.strftime("%Y-%m-%d", t_)>>> t_str'2014-05-18'>>> 

那么怎么把一个字符串转化为时间戳呢?

思路是:字符串—>struct_time—>时间戳

>>> t_str'2014-05-18'>>> t_=time.strptime(t_str, "%Y-%m-%d")>>> t_time.struct_time(tm_year=2014, tm_mon=5, tm_mday=18, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=138, tm_isdst=-1)>>> t=time.mktime(t_)>>> t1400342400.0>>> 
看,这就是个逆过程,形态很统一,是不是很简单呢。。。

当然啦,我们在清楚的时候查询官方文档是最准确,最靠谱的啦。

python2.7官方文档






0 0