# -*- coding: utf-8 -*- #时区设置 import pytz import datetime pytz.country_timezones('cn') #查看当前时区 #['Asia/Shanghai', 'Asia/Harbin', 'Asia/Chongqing', 'Asia/Urumqi', 'Asia/Kashgar'] tz = pytz.timezone('Asia/Shanghai') #设置时区 print datetime.datetime.now(tz) #当前时区时间 print datetime.datetime.strftime(datetime.datetime.now(tz),"%Y-%m-%d %H:%M:%S") #当前时区时间 ##########################分隔符########################## from datetime import datetime import time # 取当前时间,返回string类型 now_str = time.strftime("%Y-%m-%d %H:%M:%S") print (type(now_str)) print now_str print '---' # 取当前时间,返回datetime类型 print (type(datetime.now())) print datetime.now() print '---' # string -> datetime time_type = datetime.strptime(now_str, "%Y-%m-%d %H:%M:%S") print type(time_type) print time_type print '---' # datetime -> string str_type = datetime.strftime(time_type, "%Y-%m-%d %H:%M:%S") print type(str_type) print str_type #计算时间间隔 starttime = datetime.now() endtime = datetime.now() print (endtime - starttime).seconds # 构造datetime对象 new_dt = datetime(2005, 2, 16) print type(new_dt) print new_dt # 日期计算,这里需要datetime,而不是datetime.datetime yesterday_date = datetime.datetime.now() - datetime.timedelta(days=1) yesterday_str = datetime.datetime.strftime(yesterday_date, "%Y%m%d") # datetime to timestamp import time int(time.mktime(dt.timetuple())) # timestamp to datetime dt = datetime.fromtimestamp(timestamp)