使用之前import:
import time,datetime
下面的函数在python2.7里可以正常运行,但python2.4可能不支持某些方法。比如python2.4.3中报错:
AttributeError: type object 'datetime.datetime' has no attribute 'strptime'
格式化当前时间则为:
首选:time.strftime('%Y-%m-%d %H:%M:%S')
其次:datetime.datetime.strftime(datetime.d atetime.now(), '%Y-%m-%d %H:%M:%S')
最后:str(datetime.datetime.now())[:19]
获取日期差:
oneday = datetime.timedelta(days=1)
today = datetime.date.today()
yesterday = datetime.date.today() - oneday
tomorrow = datetime.date.today() + oneday
获取今天零点的时间:
today_zero_time = datetime.datetime.strftime(today, '%Y-%m-%d %H:%M:%S')
print today_zero_time
2013-05-21 00:00:00
获取时间差:
oneday = datetime.timedelta(days=1)
today_time = datetime.datetime.now()
yesterday_time = datetime.datetime.now() - oneday
tomorrow_time = datetime.datetime.now() + oneday
注意时间是浮点数,带毫秒。如下:
print tomorrow_time
2013-05-22 10:34:43.873844
那么要获取当前时间,需要格式化一下:
oneday = datetime.timedelta(days=1)
today_time = datetime.datetime.now()
yesterday_time = datetime.datetime.now() - oneday
tomorrow_time = datetime.datetime.now() + oneday
tomorrow_time = datetime.datetime.strftime(today_time, '%Y-%m-%d %H:%M:%S')
运行结果如下所示:
print tomorrow_time
2013-05-21 10:34:43
获取上个月最后一天:
last_month_last_day = datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1)
字符串格式转秒数:
expire_time = "2013-05-21 09:50:35"
d = datetime.datetime.strptime(expire_time,"%Y-%m-%d %H:%M:%S")
time_sec_float = time.mktime(d.timetuple())
print time_sec_float
1369101035.0
注意python里获取到的是float类型的秒数,而不是整形。如果要获得整数,可以用int(time_sec_float)
秒数转字符串:
time_sec = time.time()
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time_sec))
python的时间转换函数搞得太抽象复杂,因此我包装了一个函数,传入字符串可以获取到时间的各种格式,传入秒数可以获取字符串格式时间(这个是很简单的),还传入两个字符串格式的时间,以计算他们的时间差。
Python代码
#coding=gbk
import time, datetime
# 传入一个字符串格式的时间2013-05-21 14:31:23,可以得到各种格式的时间
class TIMEFORMAT:
def __init__(self, time_string="1970-1-1 00:00:00"):
self.time_string = self._format_time_string(time_string)
def _format_time_string(self, time_string):
return time.strftime("%Y-%m-%d %H:%M:%S", self.get_struct(time_string))
@property
def time_struct(self):
return self.get_struct(self.time_string)
def get_struct(self, time_string):
return time.localtime(self.get_seconds(time_string))
@property
def seconds(self):
return self.get_seconds(self.time_string)
def get_seconds(self, time_string):
d = datetime.datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S")
return time.mktime(d.timetuple())
def get_string(self, time_sec):
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time_sec))
# 对于中国的时间,是1970-01-01 08:00:00
def check_diff_time(self, t1, t2):
sec1 = int(self.get_seconds(t1))
sec2 = int(self.get_seconds(t2))
if sec1 > sec2:
secdiff = sec1 - sec2
else:
secdiff = sec2 - sec1
d = self.get_struct(self.get_string(secdiff))
day = d.tm_mday
hour = d.tm_hour
if d.tm_hour < 8:
day -= 1
hour = 24 + (d.tm_hour - 8)
else:
hour = d.tm_hour - 8
return {
"year" :d.tm_year - 1970,
"month" :d.tm_mon - 1,
"day" : day - 1,
"hour" : hour,
"min" : d.tm_min,
"sec" : d.tm_sec,
}
if __name__ == "__main__":
t1 = TIMEFORMAT("2015-04-01 12:23:23")
t2 = TIMEFORMAT("2014-03-10 22:23:23")
print t1.seconds
print t2.seconds
d = t1.check_diff_time(t1.time_string, t2.time_string)
print "%s 和 %s 时间差为:%s年%s月%s天%s小时%s分%s秒" %(t1.time_string, t2.time_string, d["year"], d["month"], d["day"], d["hour"], d["min"], d["sec"])