首页 > 编程 > Python > 正文

python time datetime模块使用方法记录

2019-11-06 07:34:45
字体:
来源:转载
供稿:网友
import timeimport datetime#time datetime使用方法备份PRint(time.clock())# 4.665275792443746e-07 返回处理器时间print(time.process_time())# 0.0780005print(time.time())# 1488616321.8451998 返回当前时间戳 <class 'float'>print(time.ctime())# Sat Mar 4 16:34:51 2017 格式化返回系统时间 <class 'str'>print(time.ctime(887665))# Sun Jan 11 14:34:25 1970print(time.ctime(time.time() - 60*60*24 ))# Fri Mar 3 16:39:17 2017 输出前一天print(time.gmtime())# time.struct_time(tm_year=2017, tm_mon=3, tm_mday=4, tm_hour=8, tm_min=41, tm_sec=32, tm_wday=5, tm_yday=63, tm_isdst=0)# <class 'time.struct_time'> 格林尼治时间print(time.localtime())# time.struct_time(tm_year=2017, tm_mon=3, tm_mday=4, tm_hour=16, tm_min=43, tm_sec=43, tm_wday=5, tm_yday=63, tm_isdst=0)# <class 'time.struct_time'> 当地时间# !!此时时间格式为struct_timeprint(time.mktime(time.localtime()))# 1488617178.0# 将struct_time时间转化为float格式的时间print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time() - 60*60*24)))# 2017-03-03 16:59:15# 将struct_time转化为字符串类型的时间# 首先:time.time() 为float格式 time.localtime() 的输入格式即为float,输出格式为struct_time# time.strftime 又将struct_time 转化为字符串输出格式print(time.strptime('2017-03-03 16:59:15',"%Y-%m-%d %H:%M:%S"))# time.struct_time(tm_year=2017, tm_mon=3, tm_mday=3, tm_hour=16, tm_min=59, tm_sec=15, tm_wday=4, tm_yday=62, tm_isdst=-1)# 与strftime相反,输入为字符串格式,按照格式对应的字段转化为struct_time格式# '2017-03-03 16:59:15'与"%Y-%m-%d %H:%M:%S"是一一对应的。# datetimeprint(datetime.date.today(),type(datetime.date.today()))# 2017-03-04 <class 'datetime.date'># 当前日期print(datetime.date.fromtimestamp(time.time() - 60*60*24))# 2017-03-03# 将float格式的时间戳转化为<class 'datetime.date'>格式current_time = datetime.datetime.now()print(current_time)# 2017-03-04 17:20:41.851214 当前时间print(current_time.timetuple())# time.struct_time(tm_year=2017, tm_mon=3, tm_mday=4, tm_hour=17, tm_min=21, tm_sec=42, tm_wday=5, tm_yday=63, tm_isdst=-1)# 将<class 'datetime.date'> 转化为 <class 'time.struct_time'>print(current_time.replace(2012))# 2012-03-04 17:29:53.446764# 替换时间并输出newtime = datetime.datetime.now() - datetime.timedelta(days=3)print(datetime.datetime.now(),'/t',newtime)# 2017-03-04 17:32:47.736732 2017-03-01 17:32:47.736732# days=3 为3天时间 -号则表示3天前
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表