首先把字符串转换成<type 'time.struct_time'>类型
struc_time = time.strptime(“2013-06-29 11:17:11”,"%Y-%m-%d %H:%M:%S")接着把<type 'time.struct_time'> 转换为<type 'float'> 的字符串
time.mktime(struc_time)简写为
c_time = time.mktime(time.strptime(“2013-06-29 11:17:11”,"%Y-%m-%d %H:%M:%S"))
与mktime想对应的为localtime 把<type 'float'> 的字符串 转换为<type 'time.struct_time'>类型
value = time.localtime(s_time_str)
time.strftime('%Y-%m-%d %H:%M:%S',value)
import time,datetime s = '(2011-07-01 17:38:49)' s = s.lstrip('(').rstrip(')') d = datetime.datetime.strptime(s,"%Y-%m-%d %H:%M:%S") #格式符参考下表 print time.mktime(d.timetuple())
方法1
import datetime now = datetime.datetime.now() now_time = datetime.datetime.strftime(now,'%Y年%m月%d日 %H:%M:%S ')
方法 2
import time now = time.time() now_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(now))
month_ago = datetime.datetime.now()-datetime.timedelta(days=30) month_ago = datetime.datetime.strftime(month_ago,'%Y-%m-%d %H:%M:%S')
python中时间日期格式化符号:
%y 两位数的年份表示(00-99)%% %号本身
本周星期一和星期天的日期
this_week_start_dt = date1-datetime.timedelta(days=date1.weekday()) this_week_start_dt = this_week_start_dt.strftime('%Y-%m-%d') this_week_end_dt = date1+datetime.timedelta(days=6-date1.weekday())
last_week_start_dt = date1-datetime.timedelta(days=date1.weekday()+7) last_week_end_dt = date1-datetime.timedelta(days=date1.weekday()+1)
y=date1.year m = date1.month month_start_dt = datetime.date(y,m,1) if m = 12: month_end_dt = datetime.date(y+1,1,1) - datetime.timedelta(days=1) else: month_end_dt = datetime.date(y,m+1,1) - datetime.timedelta(days=1)
if m==1: #如果是1月 start_date=datetime.date(y-1,12,1) else: start_date=datetime.date(y,m-1,1) end_date=datetime.date(y,m,1) - datetime.timedelta(days=1)
y=date1.year m = date1.month if month in (1,2,3): quarter_start_dt = datetime.date(y,1,1) quarter_end_dt = datetime.date(y,4,1) - datetime.timedelta(days=1) elif month in (4,5,6): quarter_start_dt = datetime.date(y,4,1) quarter_end_dt = datetime.date(y,7,1) - datetime.timedelta(days=1) elif month in (7,8,9): quarter_start_dt = datetime.date(y,7,1) quarter_end_dt = datetime.date(y,10,1) - datetime.timedelta(days=1) else: quarter_start_dt = datetime.date(y,10,1) quarter_end_dt = datetime.date(y+1,1,1) - datetime.timedelta(days=1)
quarter_days = (quarter_end_dt - quarter_start_dt).days +1 quarter_rem = (quarter_end_dt - date1).days