1.time模块:
time.time() # 返回当前时间的时间戳(1970纪元后经过的浮点秒数)
time.localtime([ sec ]) # 接收时间戳(默认为当前时间),返回struct_time对象
time.strftime(format[, t]) # 接收时间元组(默认为当前时间),并返回字符串表示的当地时间,格式由参数format决定
time.strptime(string[, format]) # 根据指定的格式(与字符串的格式保持一致)把一个时间字符串解析为时间元组,返回struct_time对象
time.mktime(t) # 接收struct_time对象,返回时间戳
time.sleep(sec) # 推迟调用线程的运行,参数sec指秒数,表示进程挂起的时间

2.datetime模块:
datetime.date # 表示日期的类, 常用的属性有year, month, day
datetime.time # 表示时间的类, 常用的属性有hour, minute, second, microsecond
datetime.datetime # 表示日期时间的类
datetime.timedelta # 表示时间间隔,即两个时间点之间的长度

date类:
datetime.date(year, month, day) # 构造函数,返回date对象
datetime.date.today() # 返回表示当前本地日期的date对象
datetime.date.fromtimestamp(t) # 接收时间戳,返回date对象
datetime.date.fromordinal(ordinal) # 接收Gregorian日历时间,返回date对象

date类提供的实例方法和属性:
t = time.time()
date = datetime.date.fromtimestamp(t)
print date.year, date.month, date.day # 年,月,日
print date.replace(2018,1,1) # 返回一个指定年,月,日的date(原有对象仍保持不变)
print date.timetuple() # 返回日期对应的time.struct_time对象
print date.toordinal() # 返回日期对应的Gregorian Calendar日期
print date.weekday() # 返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此类推
print date.isoweekday() # 返回weekday,如果是星期一,返回1;如果是星期2,返回2,以此类推
print date.isocalendar() # 返回格式如(year,month,day)的元组
print date.isoformat() # 返回格式如'YYYY-MM-DD’的字符串
print date.strftime('%Y-%m') # 自定义格式化字符串
date可以加上或减去datetime.timedelta()
date还可以进行大小比较

 

datetime类:
datetime是date与time的结合体,包括date与time的所有信息
datetime.datetime (year, month, day[ , hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] ) # 构造函数,返回datetime对象
datetime.datetime.today() # 返回一个表示当前本地时间的datetime对象
datetime.datetime.fromtimestamp(timestamp[, tz]) # 根据时间戮创建一个datetime对象,参数tz指定时区信息
datetime.datetime.strptime(str, "%Y-%m-%d %H:%M:%S") # 将格式字符串转换为datetime对象

datetime类提供的实例方法和属性
t = time.time()
datetime = datetime.datetime.fromtimestamp(t)
print datetime.date() # 获取date对象
print datetime.time() # 获取time对象
其余的实例方法和date类似
和date一样,也可以对两个datetime对象进行比较,或者相减返回一个时间间隔对象,或者日期时间加上一个间隔返回一个新的日期时间对象

posted on 2018-02-08 23:34  acgame  阅读(165)  评论(0编辑  收藏  举报