python基础篇--time,datetime(日期和时间)

日期和时间(time, datetime)

获取当前时间:
import time
import datetime

localtime = time.localtime(time.time())
print localtime
# 输出结果:
# time.struct_time(tm_year=2017, tm_mon=1, tm_mday=6, tm_hour=10, tm_min=50, tm_sec=7, tm_wday=4, tm_yday=6, tm_isdst=0)

详解:
参数 内容
tm_year 年  2017
tm_mon 月 1-12
tm_mday 日 1-31
tm_hour 小时 0-23
tm_min 分钟 0-59
tm_sec 秒  0-61(60或61是闰秒)
tm_wday 0-6(0是周一)
tm_yday 1-366(当年的第几天)
tm_isdst -1,0,1,-1是否为夏令时的旗帜

获取格式化的时间:
import time
import datetime

print time.asctime()
print time.strftime('%Y-%m-%d %H:%M:%S')
print datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
print str(datetime.datetime.now())[:19]
# 输出结果:
# Fri Jan 06 11:17:25 2017
# 2017-01-06 11:17:25
# 2017-01-06 11:17:25
# 2017-01-06 11:17:25

时间转化为时间格式:
import time
import datetime

s_time = "2017-01-06 11:11:24"
d_time = datetime.datetime.strptime(s_time, "%Y-%m-%d %H:%M:%S")
print 'type:%s , d_time:%s' % (type(d_time), d_time)
# 输出结果:
# type: , d_time:2017-01-06 11:11:24

获取时间差:
获取某段时间
import time
import datetime

print datetime.timedelta(milliseconds=1)  # 1 毫秒
print datetime.timedelta(seconds=1)  # 1秒
print datetime.timedelta(minutes=1)  # 1分钟
print datetime.timedelta(hours=1)  # 1小时
print datetime.timedelta(days=1)  # 1天
print datetime.timedelta(weeks=1)   # 一个星期7天
# 输出结果:
# 0:00:00.001000
# 0:00:01
# 0:01:00
# 1:00:00
# 1 day, 0:00:00
# 7 days, 0:00:00

计算时间差:
import time
import datetime

oneday = datetime.timedelta(days=1)  # 1天时间
today = datetime.date.today()  # 今天时间
yesterday = datetime.date.today() - oneday
tomorrow = datetime.date.today() + oneday
today_zero_time = datetime.datetime.strftime(today, '%Y-%m-%d %H:%M:%S')

print yesterday
print tomorrow
print today_zero_time
# 输出结果
# 2017-01-12
# 2017-01-14
# 2017-01-13 00:00:00




你可能感兴趣的:(python基础篇)