Python time , datetime 模块, 时间处理

time 模块

time.time() #返回当前系统的时间戳, unix 时间戳。

time.ctime() #输出 'Tue Jul 5 09:24:03 2016' 这种格式的时间

time.ctime(时间戳) #将括号里的 时间戳转 换成 Tue 格式.


time.gmtime() #输出当前时间 struct_time 格式, 零时区

time.localtime() #返回当前系统的时间 struct_time 格式,本地系统时区。

time.mktime(time.localtime()) #将 struct_time 格式,转换成 时间戳, 括号里必须有一个值。


time.strftime("%Y-%m-%d %H:%M:%S") # 格式化 时间输出。%Y 年, %m 月, %d 日, %H 时, %M 分,%S秒


time.strptime("2016-07-05", "%Y-%m-%d") #将 格式化输出,转换成 struct_time 格式。


指定日期 字符串格式 转换成 时间戳

首先获取指定日期的 struct_time 格式。
a = time.strptime(time.strftime("%Y-%m-10"), "%Y-%m-%d") #当前月份的十号

time.mktime(a) # 将 struct_time 格式 转换成 时间戳。

 

 

 

 

datetime 模块

print(datetime.date.today()) # 输出 2016-07-05 这种格式

print(datetime.date.fromtimestamp(time.time())) #将当前时间戳转换成 2016-07-05 这种格式


a = datetime.datetime.now()
print(a) #输出当前时间 2016-07-05 09:59:31.945928

print(a.timetuple()) #输出当前时间 struct_time 格式。


将 struct_time 格式,转换成时间戳。

time.mktime(a.timetuple())


print(a.replace(2016,7,10)) # 输出指定时间 2016-07-10 10:51:07.454981


a = datetime.datetime.strptime("2016-07-05 11:00", "%Y-%m-%d %H:%M") # 将字符串 转换成 时间格式

 

时间的 加减:

new_date = datetime.datetime.now() + datetime.timedelta(days=10) # 现在的天数 加10天。

new_date = datetime.datetime.now() + datetime.timedelta(days=-10) # 现在的天数 减10天。

new_date = datetime.datetime.now() + datetime.timedelta(hours=-10) # 现在的时间 减10小时。

new_date = datetime.datetime.now() + datetime.timedelta(seconds=120) # 现在的时间 加120分钟。

  月份相加


  local_date = datetime.date.today() # 输出当前时间


  new_date = datetime.date(local_date.year,local_date.month+3,local_date.day) # 当前时间增加 3个月,(day 不能为 31号 否则就报错)

 

时间的比较

 

b1 = time.time()                                                              # 当前时间的时间戳
b2 = time.mktime(time.strptime(time.strftime("%Y-%m-10"), "%Y-%m-%d"))        # 指定时间的时间戳
b3 = datetime.date.fromtimestamp(b2)                                          # 指定时间时间戳转换成 字符串时间格式
if b1 > b2:                                                                   # 时间戳 比较
    new_date = datetime.date(b3.year,b3.month+1,b3.day)                       # b1 大于 b2 new_date 等于 指定日期 加 一个月。
else:
  new_date = b3 # 小于或等于 new_date 等于 指定日期                                           

 

posted @ 2016-07-05 11:17  丶小炒肉  阅读(202)  评论(0)    收藏  举报