http://canlynet.iteye.com/blog/1543184
使用之前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的时间转换函数搞得太抽象复杂,因此我包装了一个函数,传入字符串可以获取到时间的各种格式,传入秒数可以获取字符串格式时间(这个是很简单的),还传入两个字符串格式的时间,以计算他们的时间差。