1.时间戳转时间
1 import datetime 2 3 print(datetime.datetime.fromtimestamp(1487760447.27658))
2.时间戳转时间格式
1 import datetime 2 3 print(datetime.datetime.fromtimestamp(1487760447.27658).strftime('%Y-%m-%d %H:%M:%S')
3.字符串时间转换成时间
1 import datetime 2 3 s = "2015-06-15 14:00:00" 4 t = datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
4.时间转成字符串时间
import datetime t = datetime.datetime.now() s = t.strftime('%Y-%m-%d %H:%M:%S')
5.时间转换成时间戳
1 import time 2 import datetime 3 4 now = datetime.datetime.now() 5 print(time.strftime('%s')) # for python2.x 6 print(datetime.datetime.timestamp(now)) # for python3.x
6.向前/向后若干天
1 import datetime 2 3 from dateutil.relativedelta import relativedelta 4 5 now = datetime.datetime.now() 6 # 相差delay_days 7 delay_days = 5 8 print(now-datetime.timedelta(days=delay_days)) 9 # 相差delay_months 10 delay_months = 5 11 print(now-relativedelta(months=delay_months))
6.两个时间点相差日期
from datetime import datetime from dateutil.relativedelta import relativedelta date1 = datetime.strptime('2011-08-15 12:00:00', '%Y-%m-%d %H:%M:%S') date2 = datetime.strptime('2012-02-15', '%Y-%m-%d') date_delta = relativedelta(date1, date2) print date_delta.years, date_delta.months, date_delta.weeks, date_delta.days