datetime使用技巧

import datetime


now = datetime.datetime.now()  # 得到当前时间
print(now)
now2 =now.strftime("%y/%m/%d %H:%M:%S")  # datetime转字符串, 格式化字符串
print(now2)
yesterday = datetime.datetime.now() - datetime.timedelta(days=1)  # 得到昨天
yesterday2 = datetime.datetime.now() + datetime.timedelta(days=-1)  # 得到昨天 第二种方式
print(yesterday)
print(yesterday2)

delta = now - yesterday  # datetime可以直接加减,得到datetime.timedelta对象
print(delta)
print(type(delta))
print(delta.days)
print(delta.seconds)

str_ = "2019-09-5"
ret = datetime.datetime.strptime(str_, "%Y-%m-%d")  # 将str转为datetime对象
print(ret)
print(type(ret))



 

你可能感兴趣的:(python技巧,datetime)