标准库datetime
datetime模块
对日期、时间、时间戳的处理;
datetime类
类方法:
today() 返回本地时区当前时间的datetime对象
now(tz=None) 返回当前时间的datetime对象,时间到微秒,如果tz为None,返回和today()一样
utcnow() 没有时区的当前时间
fromtimestamp(timestamp,tz=None) 从一个时间戳返回一个datetime对象
datetime对象
timestamp() 返回一个到微秒的时间戳
时间戳:格林威治时间1970年1月1日0点到现在的秒数
datetime.datetime.now().timestamp()
1534767645.707461
构造方法datetime.datetime(2016,12,6,16,29,43,79043)
year、month、day、hour、minute、second、microsecond,取datetime对象的年月日时分秒及微秒
weekday() 返回星期的天,周一0,周日6
isoweekday() 返回星期的天,周一1,周日7
date() 返回日期date对象
time() 返回时间time对象
replace() 修改并返回新的时间
isocalendar() 返回一个三元组(年,周数,周的天)
日期格式化**:
类方法strptime(date_string,format),返回datetime对象
对象方法strftime(format),返回字符串
字符串format函数格式化
timedelta对象(时间差)
datetime2 = datetime1 + timedelta
datetime2 = datetime1 - timedelta
timedelta = datetime1 - datetime2
构造方法:
datetime.timedelta(day=0,seconds=0,microseconds=0,milliseconds=0,
minutes=0,hours=0,weeks=0)
year = datetime.timedelta(days=365)
total_seconds() 返回时间差的总秒数
例:
h = datetime.timedelta(hours=24)
print(h)
d = datetime.datetime.now()
s = d - h
print(s)
print((d - s).total_seconds())# 用现在的时间减去(时间差后的时间).total_seconds
标准库time
time:
time.sleep(secs) 将调用线程挂起指定的秒数;
import time
time.sleep(5)
print("Hello, Python")
举例说明:
import datetime
print(datetime.datetime.now()) # 模块.类.方法
print(datetime.datetime.today())
a = datetime.datetime.now().timestamp()# datetime对象,返回时间戳
print(datetime.datetime.fromtimestamp(a))# 从一个时间戳返回一个datetime对象
a = datetime.datetime(2016, 2, 1)# datetime对象的构建
print(a)
print(a.year)
print(a.weekday())
print(a.isoweekday())
print(a.time())
print(a.replace(2018, 1, 1, 12, 12))
a = a.replace(2018, 1, 1, 12, 12)
print(a.isocalendar())
日期格式化**
dt = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
print(dt)
print(dt.strftime("%Y-%m-%d %H:%M:%S"))
print("{0:%Y}/{0:%m}/{0:%d} {0:%H}::{0:%M}::{0:%S}".format(dt))
转载于:https://blog.51cto.com/limingyu/2161872