Python时间模块

time模块

import time

# 获取当前时间,返回时间元组
time_ = time.localtime()
# time.struct_time(tm_year=2017, tm_mon=9, tm_mday=13, tm_hour=19, tm_min=24, tm_sec=6, tm_wday=2, tm_yday=256, tm_isdst=0)

# 将时间戳转换成时间元组
time_array = time.localtime(1405301846.905501)
#time.struct_time(tm_year=2014, tm_mon=7, tm_mday=14, tm_hour=9, tm_min=37, tm_sec=26, tm_wday=0, tm_yday=195, tm_isdst=0)

# 将时间元组转换成指定时间格式
time_ = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())  # 2017-10-09 17:07:20

# 把某种格式的时间转换成时间元组
time_ = time.strptime('20170901', '%Y%m%d') 
# time.struct_time(tm_year=2017, tm_mon=9, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=244, tm_isdst=-1)

# 时间戳
time_ = time.time()    # 1505301846.905501

datetime模块

import datetime

# 获取当前的时间
time_ = datetime.datetime.now()  # 2017-10-09 16:59:27.313610
time_ = datetime.datetime.today()   # 2017-10-09 16:59:27.313610

# 获取当天的日期
date_ = datetime.date.today()      # 2017-10-09

# 获取前一天的日期
date_ = datetime.date.today() - datetime.timedelta(days=1)

# 获取一个小时之前的时间
time_ = datetime.datetime.now() - datetime.timedelta(hours=1)
posted @ 2017-10-09 20:13  cnkai  阅读(293)  评论(0编辑  收藏  举报