python_81_标准库_时间模块

'''
标准库:
1.time
    时间的三种表示方法:a:时间戳(timestamp)  b:格式化的时间字符串  c:元组(struct_time)共九个元素
    time.struct_time(tm_year=2018, tm_mon=2, tm_mday=7, tm_hour=22, tm_min=28, tm_sec=9, tm_wday=2, tm_yday=38, tm_isdst=0不是夏令时)
'''
import time
print(time.localtime())#元组(struct_time)
print(time.time())#获取时间戳(timestamp)

help(time)#查看time模块使用方法  注:weekday (0-6, Monday is 0)

print(time.timezone)#世界标准时间UTC与本地标准时间的差值,单位:s
print(time.timezone/3600)#结果是-8,因为中国在东八区
print(time.altzone)#世界标准时间UTC与夏令时时间的差值,单位:s
print(time.daylight)#是否使用了夏令时
time.sleep(2)#程序睡两秒

'''
将时间戳(timestamp)转表示换成元组(struct_time)表示形式:
gmtime:结果为UTC时区
localtime:结果为本地时区(中国:UTC+8时区)
'''
#time.gmtime()将时间戳(timestamp)转表示换成元组(struct_time)表示,括号内写时间戳(timestamp),若不写,则传入当前时间,将时间转换成UTC时间
print(time.gmtime())
print(time.gmtime(3))
#time.localtime将时间戳(timestamp)转表示换成元组(struct_time)表示,括号内写时间戳(timestamp),若不写,则传入当前时间,将时间转换成本地时间
print(time.localtime())
print(time.localtime(3))
x=time.localtime()
print(x.tm_year,x.tm_mon)

'''
将元组(struct_time)表示转换成时间戳(timestamp)表示形式:mktime
'''
print(time.mktime(x))

'''
将元组(struct_time)表示转换成格式化的字符串表示形式:
A:strftime('格式',struct_time)---->‘格式化的字符串’
B:asctime   将struct_time转换成%a %b %d %H:%M:%S %Y
'''
print(help(time.strftime))
print(time.strftime('%d-%m-%Y,%H:%M:%S',x))# %Y:x.tm_year  %m:x.tm_mon
print(time.strftime('%Y-%m-%d,%H:%M:%S',time.localtime()))

print(help(time.asctime))
# Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
# When the time tuple is not present, current time as returned by localtime() is used.
print(time.asctime())


'''
将格式化的字符串表示转换成元组(struct_time)表示形式:
strptime('格式化的字符串',格式)---->‘struct_time’
'''
print(help(time.strptime))
print(time.strptime('2018-02-07,23:11:34','%Y-%m-%d,%H:%M:%S'))#x.tm_year=2018  x.tm_mon=02  ....

'''
将时间戳(timestamp)转化成字符串表示形式:
ctime   将时间戳(timestamp)转换成%a %b %d %H:%M:%S %Y
'''
print(help(time.ctime))
# Convert a time in seconds since the Epoch to a string in local time.
# This is equivalent to asctime(localtime(seconds)).
# When the time tuple is not present, current time as returned by localtime() is used.
print(time.ctime())


# 2.datetime
import datetime
print(datetime.datetime.now())
'注:datetime.timedelta()必须和datetime.datetime.now()连用'
print(datetime.datetime.now()+datetime.timedelta(3))#当前时间+3天
print(datetime.datetime.now()+datetime.timedelta(-3))#当前时间-3天
print(datetime.datetime.now()+datetime.timedelta(hours=3))#当前时间+3小时
print(datetime.datetime.now()+datetime.timedelta(hours=-3))#当前时间-3小时
print(datetime.datetime.now()+datetime.timedelta(minutes=30))
'修改当前时间'
t=datetime.datetime.now()
print(t.replace(minute=3,hour=3))#时间替换

 

posted @ 2018-02-08 00:09  耐烦不急  阅读(204)  评论(0编辑  收藏  举报