首页 > 代码库 > 20.time与datetime模块
20.time与datetime模块
time与datetime模块
- 时间戳 1970年1月1日之后的秒,即:time.time()
- 格式化的字符串 2014-11-11 11:11, 即:time.strftime(‘%Y-%m-%d‘)
- 结构化时间 元组包含了:年、日、星期等... time.struct_time 即:time.localtime()
import time time.sleep(5) ‘‘‘ 程序停止5秒 ‘‘‘ print(time.time()) ‘‘‘ 时间戳:1495539499.9574285 ‘‘‘ print(time.ctime()) # 字符串格式 ‘‘‘ Tue May 23 19:38:19 2017 ‘‘‘ print(time.ctime(time.time()-86400)) # 减去一天的秒数,将时间戳转换成字符串时间 ‘‘‘ Mon May 22 19:38:19 2017 ‘‘‘ # 将时间戳转换成时间对象格式 time_obj = time.gmtime(time.time()) print(time_obj) ‘‘‘ time.struct_time(tm_year=2017, tm_mon=5, tm_mday=23, tm_hour=11, tm_min=38, tm_sec=19, tm_wday=1, tm_yday=143, tm_isdst=0) ‘‘‘ print(time_obj.tm_year) ‘‘‘ 2017 ‘‘‘ print(str(time_obj.tm_year) + ‘-‘ + str(time_obj.tm_mon) + ‘-‘ + str(time_obj.tm_mday)) ‘‘‘ 2017-5-23 ‘‘‘ # 字符串格式化 print("%s-%s-%s %s:%s" % (time_obj.tm_year, time_obj.tm_mon, time_obj.tm_mday, time_obj.tm_hour, time_obj.tm_min)) ‘‘‘ 2017-5-23 11:38 ‘‘‘ print("%d-%f-%d %d:%d" % (time_obj.tm_year, time_obj.tm_mon, time_obj.tm_mday, time_obj.tm_hour, time_obj.tm_min)) ‘‘‘ 2017-5.000000-23 11:38 %d只能接收整型数剧,但是%s都可以各种类型的数据 ‘‘‘ # 本地时间 输出一个时间对象 print(time.localtime(time.time())) ‘‘‘ time.struct_time(tm_year=2017, tm_mon=5, tm_mday=23, tm_hour=19, tm_min=38, tm_sec=19, tm_wday=1, tm_yday=143, tm_isdst=0) ‘‘‘ # 将时间对象转换成时间戳 print(time.mktime(time.localtime())) ‘‘‘ 1495539499.0 ‘‘‘ # 将时间对象格式转换成指定的字符串格式 print(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())) ‘‘‘ 2017-05-23 11:38:19 ‘‘‘ print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) ‘‘‘ 2017-05-23 19:38:19 ‘‘‘ # 将字符串格式转换成时间对象格式 print(time.strptime("2016-01-28", "%Y-%m-%d")) ‘‘‘ time.struct_time(tm_year=2016, tm_mon=1, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=28, tm_isdst=-1) ‘‘‘ import datetime print(datetime.date.today()) ‘‘‘ 2017-05-23 ‘‘‘ print(datetime.date.fromtimestamp(time.time()-664000000)) ‘‘‘ 1996-05-08 ‘‘‘ current_time = datetime.datetime.now() print(current_time) ‘‘‘ 2017-05-23 19:38:20.001431 ‘‘‘ print(current_time.timetuple()) # 返回时间对象格式 ‘‘‘ time.struct_time(tm_year=2017, tm_mon=5, tm_mday=23, tm_hour=19, tm_min=38, tm_sec=20, tm_wday=1, tm_yday=143, tm_isdst=-1) ‘‘‘ print(current_time.replace(2014, 12, 12))# 输出当前时间,指定值被替换 ‘‘‘ 2014-12-12 19:38:20.001431 ‘‘‘ str_to_date = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")#将字符串转换成日期的字符串格式 print(str_to_date) ‘‘‘ 2006-11-21 16:30:00 ‘‘‘ # 时间的加减 用得很多 new_date0 = datetime.datetime.now() + datetime.timedelta(days=-10) #减10天 ‘‘‘ ‘‘‘ new_date1 = datetime.datetime.now() + datetime.timedelta(hours=-10) #减10个小时 ‘‘‘ ‘‘‘ new_date2 = datetime.datetime.now() + datetime.timedelta(seconds=-10) # 减10秒 ‘‘‘ ‘‘‘
20.time与datetime模块
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。