Python的时间函数是平时开发时最常用的东西了,很多时候都要和它们打交道。平时用惯了PHP的时间函数,回到Python还是觉得不方便,而且不便于记忆,导致我经常回去Google一下。这次直接记录在我的博客里,加强一下记忆,也帮助以后忘了查询。
import time
# 获取当前时间(时间戳)
>>>time.time()
1429691242.294228
# 获取当前时间(字符串)
>>>time.strftime('%Y-%m-%d %H:%M:%S')
'2015-04-22 16:27:51'
# 获取localtime
>>>time.localtime()
time.struct_time(tm_year=2015, tm_mon=4, tm_mday=22, tm_hour=16, tm_min=28, tm_sec=12, tm_wday=2, tm_yday=112, tm_isdst=0)
>>>time.localtime(1429691242.294228)
time.struct_time(tm_year=2015, tm_mon=4, tm_mday=22, tm_hour=16, tm_min=27, tm_sec=22, tm_wday=2, tm_yday=112, tm_isdst=0)
# 将时间戳转换为localtime,再将localtime转换为时间字符串
>>>x = time.localtime(time.time())
time.struct_time(tm_year=2015, tm_mon=4, tm_mday=22, tm_hour=16, tm_min=35, tm_sec=54, tm_wday=2, tm_yday=112, tm_isdst=0)
>>>time.strftime('%Y-%m-%d %H:%M:%S', x)
'2015-04-22 16:35:54'
# 将时间字符串转换为localtime
>>>x = time.strftime('%Y-%m-%d %H:%M:%S'); x
'2015-04-22 16:31:21'
>>>time.strptime(x, '%Y-%m-%d %H:%M:%S')
time.struct_time(tm_year=2015, tm_mon=4, tm_mday=22, tm_hour=16, tm_min=31, tm_sec=21, tm_wday=2, tm_yday=112, tm_isdst=-1)
# 将localtime转换为时间戳
>>>x = time.localtime(); x
time.struct_time(tm_year=2015, tm_mon=4, tm_mday=22, tm_hour=16, tm_min=32, tm_sec=19, tm_wday=2, tm_yday=112, tm_isdst=0)
>>>time.mktime(x)
1429691539.0
# 将时间字符串转换为时间戳
>>>x = time.strftime('%Y-%m-%d %H:%M:%S'); x
'2015-04-22 16:32:57'
>>>time.mktime(time.strptime(x,'%Y-%m-%d %H:%M:%S'))
1429691577.0